diff options
author | Maurus Cuelenaere <mcuelenaere@gmail.com> | 2008-07-11 15:50:46 +0000 |
---|---|---|
committer | Maurus Cuelenaere <mcuelenaere@gmail.com> | 2008-07-11 15:50:46 +0000 |
commit | 14c7f45cdae826f88dc539c8c38dd95caf305731 (patch) | |
tree | 832da054b7cfb2dc6fd63339af736625f31d21aa /utils/zenutils | |
parent | 7c84ede3781c27db73403bd6302f320c76a58c8c (diff) | |
download | rockbox-14c7f45cdae826f88dc539c8c38dd95caf305731.tar.gz rockbox-14c7f45cdae826f88dc539c8c38dd95caf305731.zip |
Add zook's ZenUtils to SVN
git-svn-id: svn://svn.rockbox.org/rockbox/trunk@18010 a1c6a512-1295-4272-9138-f99709370657
Diffstat (limited to 'utils/zenutils')
147 files changed, 44667 insertions, 0 deletions
diff --git a/utils/zenutils/CMakeLists.txt b/utils/zenutils/CMakeLists.txt new file mode 100755 index 0000000000..32798747cd --- /dev/null +++ b/utils/zenutils/CMakeLists.txt @@ -0,0 +1,13 @@ +PROJECT(zenutils)
+
+SET(EXECUTABLE_OUTPUT_PATH ${zenutils_SOURCE_DIR}/bin/${CMAKE_SYSTEM_NAME})
+
+SUBDIRS(source libraries)
+
+INCLUDE_DIRECTORIES(
+ ${zenutils_SOURCE_DIR}/libraries/beecrypt-4.1.2
+ ${zenutils_SOURCE_DIR}/libraries/getpot-c++-1.1.17
+ ${zenutils_SOURCE_DIR}/libraries/pelib-0.9
+ ${zenutils_SOURCE_DIR}/libraries/zlib123
+ ${zenutils_SOURCE_DIR}/source/shared
+)
diff --git a/utils/zenutils/COPYING b/utils/zenutils/COPYING new file mode 100755 index 0000000000..d511905c16 --- /dev/null +++ b/utils/zenutils/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/utils/zenutils/bin/firmware_extract.exe b/utils/zenutils/bin/firmware_extract.exe Binary files differnew file mode 100755 index 0000000000..834adefc30 --- /dev/null +++ b/utils/zenutils/bin/firmware_extract.exe diff --git a/utils/zenutils/bin/firmware_make.exe b/utils/zenutils/bin/firmware_make.exe Binary files differnew file mode 100755 index 0000000000..df62304226 --- /dev/null +++ b/utils/zenutils/bin/firmware_make.exe diff --git a/utils/zenutils/bin/update_extract.exe b/utils/zenutils/bin/update_extract.exe Binary files differnew file mode 100755 index 0000000000..752cf2d083 --- /dev/null +++ b/utils/zenutils/bin/update_extract.exe diff --git a/utils/zenutils/bin/update_patch.exe b/utils/zenutils/bin/update_patch.exe Binary files differnew file mode 100755 index 0000000000..c3a6a808bf --- /dev/null +++ b/utils/zenutils/bin/update_patch.exe diff --git a/utils/zenutils/bin/zen_crypt.exe b/utils/zenutils/bin/zen_crypt.exe Binary files differnew file mode 100755 index 0000000000..a5dce080de --- /dev/null +++ b/utils/zenutils/bin/zen_crypt.exe diff --git a/utils/zenutils/libraries/CMakeLists.txt b/utils/zenutils/libraries/CMakeLists.txt new file mode 100755 index 0000000000..19297d7a2e --- /dev/null +++ b/utils/zenutils/libraries/CMakeLists.txt @@ -0,0 +1,3 @@ +ADD_SUBDIRECTORY(beecrypt-4.1.2)
+ADD_SUBDIRECTORY(pelib-0.9)
+ADD_SUBDIRECTORY(zlib123)
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt new file mode 100755 index 0000000000..83836af99d --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/CMakeLists.txt @@ -0,0 +1,14 @@ +PROJECT(beecrypt)
+
+# source files for beecrypt
+SET(beecrypt_srcs
+ beecrypt/blockmode.c
+ beecrypt/blowfish.c
+ beecrypt/endianness.c
+ beecrypt/hmac.c
+ beecrypt/hmacsha1.c
+ beecrypt/mp.c
+ beecrypt/sha1.c
+)
+
+ADD_LIBRARY(beecrypt ${beecrypt_srcs})
diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS new file mode 100755 index 0000000000..878abf5a3f --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/AUTHORS @@ -0,0 +1,11 @@ +BeeCrypt Cryptograpy Library: + +Bob Deblier <bob.deblier@pandora.be> + +C++ Interface: + +Bob Deblier <bob.deblier@pandora.be> + +Python Interface: + +Jeff Johson <jbj@redhat.com> diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS new file mode 100755 index 0000000000..7919f340db --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BENCHMARKS @@ -0,0 +1,73 @@ +Note: timings are average values and may vary under different conditions, +i.e. the amount of free memory, swapped memory, amount of cpu cache, etc. +I've tried to make them as accurate as possible, within limits. + +Note: many of the testing systems were provided by HP's testdrive program; +many thanks to them for giving me access to their systems. Also thanks to +SourceForge for their compile farm! + +Note: to avoid religious wars, in the table below read GNU/Linux for +Linux - I'm just a little cramped for space... + +BENCHmark Modular Exponentation (more is better): + +BeeCrypt 4.0.0 | gcc-3.3.3 | Fedora Core 2 | Athlon 64 3000+| 1 GB: 24870 +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 24566 +BeeCrypt 4.0.0 | gcc-3.2.2 | SuSE 8 EL | Opteron 1600 | 1 GB: 19460 +BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | Opteron MP 1600 | : 17230 +BeeCrypt 3.1.0 | gcc-2.96 | RedHat AS 2.1 | Itanium 2 1400 | 1 GB: 11453 +BeeCrypt 3.0.0 | gcc-3.2.2 | Debian Linux 3.0 | Itanium 2 900 | 12 GB: 7317 +BeeCrypt 3.0.0 | gcc-3.3 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 6920 [--with-arch=pentium4] +BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 6811 [--with-arch=pentium4] +BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 5858 +BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0 | Alpha EV6.7 666 | 2 GB: 5742 +BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 3280 [--with-arch=pentiumpro] +BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | POWER4+ 1200 | : 2592 +BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | P3 Xeon 900 | : 2169 +BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 1782 [--with-arch=powerpc64] +BeeCrypt 3.0.0 | gcc-3.x | RedHat Linux | zSeries 900 | : 1687 (s390x) +BeeCrypt 3.0.0 | gcc-3.3 | SuSE Linux 8.2 | Pentium 3 600 | 512 MB: 1447 [--with-arch=pentium3] +BeeCrypt 3.0.0 | gcc-3.2.2 | AIX 5.1 | POWER3-II 333 | 512 MB: 756 +BeeCrypt 3.0.0 | Forte C 5.1 | Solaris 8 | UltraSparc II 400 | 4 GB: 425 [--with-arch=sparcv8plus] +BeeCrypt 3.0.0 | | Debian Linux 3.0 | StrongARM 1110 128 | 32 MB: 341 +BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68040 33 | 52 MB: 24 +BeeCrypt 3.0.0 | gcc-2.95.4 | Debian Linux 3.0r1 | M68030 25 | 36 MB: 8 + +BENCHmark Hash Function (more is better): + +MD5 +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 190.5 MB/s +BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 137.0 MB/s [--with-arch=pentiumpro] +BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 97.2 MB/s [--with-arch=pentium4] +BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 38.8 MB/s + +SHA-1 +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 117.4 MB/s +BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 81.9 MB/s [--with-arch=pentium4] +BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 77.0 MB/s [--with-arch=pentiumpro] +BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 51.2 MB/s + +SHA-256 +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 85.1 MB/s +BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 42.4 MB/s [--with-arch=pentium4] +BeeCrypt 3.0.0 | gcc-2.96 | RedHat AS 2.1 | P4 Xeon 2400 | 4 GB: 37.8 MB/s [--with-arch=pentiumpro] +BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 33.0 MB/s + +SHA-512 +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 129.6 MB/s +BeeCrypt 4.1.0 | gcc-3.3.3 | SuSE Enterprise 9 | POWER4 1000 | 16 GB: 57.6 MB/s +BeeCrypt 4.1.0 | gcc-3.3.3 | Fedora Core 2 | P4 Xeon 2400 | 1 GB: 46.3 MB/s [--with-arch=pentium4] + +BENCHmark Block Cipher (more is better): + +AES, 128 bits +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 97.0 MB/s [ECB encrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 93.5 MB/s [CBC encrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 104.6 MB/s [ECB decrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 99.2 MB/s [CBC decrypt] + +Blowfish, 128 bits +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.4 MB/s [ECB encrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 57.7 MB/s [CBC encrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 61.4 MB/s [ECB decrypt] +BeeCrypt 4.1.0 | gcc-3.4.2 | Fedora Core 3 | Athlon 64 3000+| 1 GB: 59.3 MB/s [CBC decrypt] diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS new file mode 100755 index 0000000000..577c5adac5 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/BUGS @@ -0,0 +1,69 @@ +Legend: + - = open bug + * = fixed bug + +4.1.0: + - SuSE 9.2 (x86) compiler is buggy: the MMX-optimized version fails all + test vectors. Since all other Linux distro's handle this perfectly it's + up to them to fix this bug. + +3.1.0: + * Error in final result computation of mpextgcd_w in certain circumstances. + * PowerPC 64-bit assembler symbols aren't defined according to LSB 1.3. + +3.0.0: + - Can't seem to generate 64-bit shared libraries on AIX; use + --disable-shared on this platform for now. + - Intel icc can't cope with gcj headers. There's also a problem in + combination with aio.h; solution should be to not test gcj when using + this compiler. As a workaround, you can specify --without-javaglue. + - GCC 3.3 produces faster output for Blowfish on Pentium 4 than the + included assembler source; try coding two Blowfish rounds (without swap) + in C and compile to assembler to see how GCC accomplishes this. + +2.3.0pre: + * bug in certain instances of computing modular inverse. + * incorrectly translated intel-style assembler version of x86 mp32odd + and mp32even routines into gnu assembler format. + * base64 decoding of '+' and '/' characters is wrong. + * incorrect testing of the result of the gcd operation in mp32prndconone. + * Chinese Remainer Theorem for RSA private key operation doesn't work + * incorrect header file inclusion when --disable-threads is selected or + when no multithreading is available. + +2.2.0: + [ Released by Jeff Johnson of RedHat, Inc.; lint & doxygen enhanced version + of 2.1.0. ] + +2.1.0: + * Entropy gathering from /dev/dsp contained error; size in words of entropy + data to gather was overwritten with audio sample size - which resulted in + much less entropy. + +2.0.0: + - Chinese Remainder Theorem for RSA private key operation doesn't work; it + needs fixing. + +1.1.2: + * SHA-1 i586 assembler code uses local variables below the current stack + frame. + +1.1.1: + * discrete logarithm domain parameter generator calculations contains bugs + - was detected in this release but present since the first release. + +1.1.0: + * The javaglue produces a NullPointerException when initializing with a + null IV; this should be treated correctly, i.e. as an all zero IV. + +1.0.2: + +1.0.1: + * The Windows 2000 bug is still around + +1.0.0: + * On Windows 2000, the entropy system gets error WAVERR_BADFORMAT in + waveInOpen; So far I've been unable to determine why the system does this + for format WAVE_FORMAT_PCM. Suggestions to fix this problem are more than + welcome. + * The assembler code for SHA-1 in gnu/fips180opt.gas.i586.s contains bugs. diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS new file mode 100755 index 0000000000..7f61011475 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/CONTRIBUTORS @@ -0,0 +1,19 @@ +I would like to thank the following people (in alphabetical order): + +- Seth Arnold, for contributing to the documentation. +- Jan-Rudolph Bührmann, for helping me get started on the 64-bit multi- + precision integer library. +- Luca Filipozzi, maintainer/packager of BeeCrypt for Debian GNU/Linux. +- Jeff Johnson, the guy behind RedHat's Package Manager, who has inspired + and contributed to many of the changes for version 3.0.0; 73 de Bob. +- Jon Sturgeon, bug hunter extraordinaire. + +Further thanks go to: +- AMD, for donating a copy of "AMD x86-64 Architecture Programmer's Manual". +- ARM Ltd, for donating a copy of "ARM Architecture Reference Manual". +- HP/Compaq, for their testdrive program, which gave me the opportunity to + test and BeeCrypt on many new platforms. +- SourceForge, for their excellent open source development platform! + +Last but not least: thanks to everyone who provided bits of information, +reported bugs and provided feedback. diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING new file mode 100755 index 0000000000..a6d7d0188a --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING @@ -0,0 +1,336 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Hereny it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Section diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB new file mode 100755 index 0000000000..223ede7de3 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/COPYING.LIB @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog new file mode 100755 index 0000000000..e69de29bb2 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/ChangeLog diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL new file mode 100755 index 0000000000..bca44d042e --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/INSTALL @@ -0,0 +1,187 @@ +Basic Installation +================== + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, a file +`config.cache' that saves the results of its tests to speed up +reconfiguring, and a file `config.log' containing compiler output +(useful mainly for debugging `configure'). + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If at some point `config.cache' +contains results you don't want to keep, you may remove or edit it. + + The file `configure.in' is used to create `configure' by a program +called `autoconf'. You only need `configure.in' if you want to change +it or regenerate `configure' using a newer version of `autoconf'. + +The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. If you're + using `csh' on an old version of System V, you might need to type + `sh ./configure' instead to prevent `csh' from trying to execute + `configure' itself. + + Running `configure' takes awhile. While running, it prints some + messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + If you're building GNU make on a system which does not already have + a `make', you can use the build.sh shell script to compile. Run + `sh ./build.sh'. This should compile the program in the current + directory. Then you will have a Make program that you can use for + `make install', or whatever else. + + 3. Optionally, type `./make check' to run any self-tests that come with + the package. + + 4. Type `make install' to install the programs and any data files and + documentation. + + 5. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + +Compilers and Options +===================== + + Some systems require unusual options for compilation or linking that +the `configure' script does not know about. You can give `configure' +initial values for variables by setting them in the environment. Using +a Bourne-compatible shell, you can do that on the command line like +this: + CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure + +Or on systems that have the `env' program, you can do it like this: + env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure + +Compiling For Multiple Architectures +==================================== + + You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you must use a version of `make' that +supports the `VPATH' variable, such as GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. + + If you have to use a `make' that does not supports the `VPATH' +variable, you have to compile the package for one architecture at a time +in the source code directory. After you have installed the package for +one architecture, use `make distclean' before reconfiguring for another +architecture. + +Installation Names +================== + + By default, `make install' will install the package's files in +`/usr/local/bin', `/usr/local/man', etc. You can specify an +installation prefix other than `/usr/local' by giving `configure' the +option `--prefix=PATH'. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +give `configure' the option `--exec-prefix=PATH', the package will use +PATH as the prefix for installing programs and libraries. +Documentation and other data files will still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=PATH' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + +Optional Features +================= + + Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + +Specifying the System Type +========================== + + There may be some features `configure' can not figure out +automatically, but needs to determine by the type of host the package +will run on. Usually `configure' can figure that out, but if it prints +a message saying it can not guess the host type, give it the +`--host=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name with three fields: + CPU-COMPANY-SYSTEM + +See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the host type. + + If you are building compiler tools for cross-compiling, you can also +use the `--target=TYPE' option to select the type of system they will +produce code for and the `--build=TYPE' option to select the type of +system on which you are compiling the package. + +Sharing Defaults +================ + + If you want to set default values for `configure' scripts to share, +you can create a site shell script called `config.site' that gives +default values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Operation Controls +================== + + `configure' recognizes the following options to control how it +operates. + +`--cache-file=FILE' + Use and save the results of the tests in FILE instead of + `./config.cache'. Set FILE to `/dev/null' to disable caching, for + debugging `configure'. + +`--help' + Print a summary of the options to `configure', and exit. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`--version' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`configure' also accepts some other, not widely useful, options. + diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS new file mode 100755 index 0000000000..6c6bbd0175 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/NEWS @@ -0,0 +1,184 @@ +4.1.2: + - Fixed Cygwin DLL missing symbols problem. + - Fixed GNU-stack assembler section on some platforms (Debian-ARM). + - Fixed problem cause by include of <asm/byteorder.h>. + - Fixed SHA-384 and SHA-512 code Visual C++ compatibility. + - Improved detection of IBM ICU library version; has to be >= 2.8. + +4.1.1: + - Fixed shared library version info. + +4.1.0: + - Added SHA-384 and SHA-512 algorithms. + - Added HMAC-SHA-384 and HMAC-SHA-512 algorithms. + - Added generic SSE2 optimization for the above algorithms. + - Added more digest algorithms for PKCS#1 EMSA. + - Optimized swap32 and swap64 routines on Linux. + - Fixed missing definition in mpopt.h for s390x. + - Fixed nostackexec configuration bug. + - Fixed problem in Date::toString. + - Fixed deadlock problem which occured in certain cases where security + or crypto SPI constructor called getInstance for another security or + crypto SPI. + - Fixed a bug in the generic CBC encryption code; when called with + nblocks == 1, the feedback was set incorrectly. + - Fixed a bug in mpbsubmod; sometimes it takes multiple additions of + the modulus to get a positive number. + - Fixed PowerPC 64-bit configuration problem on Linux. + +4.0.0: + - Added a C++ API interface, modeled after Java's security & crypto API. + - Added the new GNU noexecstack feature. + - Added more x86_64 and s390x assembler routines. + - Modified i2osp, so that it only requires as many octets as there are + significant bytes in the multi-precision integers. + - Fixed a bug in the creation of rsa keypairs; code was not correctly + migrated to new calling sequence. The code now implements the method + described in IEEE P.1363. + - Fixed another bug in mpextgcd_w which sometimes returned incorrect + results. + - Fixed a bug in mprshiftlsz, which didn't work correctly when size = 1. + - Fixed a configuration problem on Tru64 Unix. + +3.1.0: + - Added wiping of private key components of keypairs before freeing. + - Fixed bug in mpextgcd_w which sometimes returned incorrect result. + - Fixed error in PowerPC 64-bit assembler symbol definitions. + +3.0.0: + - Cleaned up installed header files. + - Modified the API so that all keys can be passed as arrays of bytes. + - Modified the API so that all key sizes are given in bits. + - Modified the multi-precision integer library to work better on 64-bit + machines. + - Modified the assembly source generation mechanism, employing the m4 + macro processor. + - Added multi-precision integer vectorized assembler routines for + Itanium. + - Added multi-precision integer assembler routines for PowerPC 64-bit. + - Added multi-precision integer assembler routines for Alpha. + - Added multi-precision integer assembler routines for Opteron. + - Added multi-precision integer assembler routines for IBM zSeries 64-bit. + - Added multi-precision integer assembler routines for M68K. + - Added Jeff Johnson's python bindings. + - Added new unit tests. + - Added new benchmarking programs. + +2.3.0pre: + - Modified the header files so that the library now uses self-contained autoconf-generated configuration files; a program employing BeeCrypt can now use the symbols already tested and defined instead of having to regenerate them (thus also eliminating the risk of inconsistencies). + - Added the AES algorithm, with assembler routines for i586 and powerpc. + - Added the DSA signature algorithm. + - Added PowerPC assembler routines for blowfish. + - Added Pentium4 SSE2 assembler multiplication routines. + - Fixed the RSA CRT algorithm. + - Fixed the gas/i386 mp32even and mp32odd routines. + - Fixed a bug in modular inverse computation; thanks to Jeff Johnson of RedHat for pointing this out. + - Fixed a bug in testing the result of a gcd operation in the mp32prndconone routine. + - Fixed an ugly bug in base64 decoding. + - Fixed compatibility with the latest automake & autoconf versions. + - Replaces CPU optimization mechanism in configure script. + +2.1.0: + - Added support for automake, autoheader and libtool, which should make compiling the library even easier. + - Changed DHAES API to conform to IEEE P.1363 submission and to allow for uneven key splitting. + - Improved PKCS#5 padding routines. + - Added a hash reset to the hashFunctionContextInit function. This was pointed out by Marko Kreen. + - Fixed problem with configuring on i486-pc-linux-gnu. This was pointed out Steve O'Neill. + - Fixed problem in the C version of mp32sub where carry would sometimes be missed. This was pointed out by Jon Sturgeon. + - Revised entropy gathering system to do timeouts & asynchronous I/O where possible, to avoid hangs in case there's no noise on the audio device (i.e. digital silence), or when no data is available on devices such as /dev/random. + - Changed mp32opt i386 assembler routines for slight performance improvement. + - Changed mp32opt powerpc assembler routines for slight performance improvement. + - Changed mp32opt sparcv9 assembler routines for slight performance improvement. + - Added sparcv8 assembler routines for multi-precision integer multiplication. + - Added arm assembler routines for multi-precision integer multiplication. + - Added prototype 64-bit ia64 assembler routines for multi-precision integer operations. + - Started writing the long-awaited documentation. + +2.0.0: + - Changed mp32barrett struct and operations to be multithread-safe; this required a change in API. + - Changed hashFunction struct to incorporate internal block size parameter. + - Changed HMAC algorithm and file names to match names in RFC 2104. + - Changed SHA-1 C code for slightly faster results. + - Changed detection of entropy devices. + - Changed most void-returning functions to return int for error conditions. + - Changed beecrypt-java class names in javaglue. + - Added RSA keypair generation. + - Added RSA private & public key operations. + - Added SHA-256 hash function. + - Added HMAC-MD5 and HMAC-SHA-256 keyed hash functions. + - Added PKCS#5 padding. + - Added DHAES encryption scheme. + - Added Microsoft Visual C support, added Makefile.mak for this purpose. + - Added Solaris/Sparc Forte C 64 bit support. + - Added configure --disable-optimized option (disables assembler & processor-specific optimizations). + - Fixed bug in SHA-1 assembler code for Pentium, where local variables were used below the current stack pointer; this could cause a problem if the routine was interrupted. This was pointed out by Richard Clayton. + - Fixed bug in (certain cases of) modular inverse computation. + - Fixed buffer overrun in base64 encoding. This was pointed out by Jon Sturgeon. + - Fixed various minor bugs. + - Renamed text files to match automake conventions. + +1.1.2: + - Fixed bugs in discrete logarithm domain parameter generator. The code to make a generator of order q and (p-1) was wrong. This was pointed out by Susumu Yamamoto. + - Added MD5 hash function. + +1.1.1: + - Changed autoconfig script for easier porting. + - Changed sources for easier compilation on Microsoft Visual C++; no assembler-optimization on this platform yet. + - Fixed bug in javaglue when passing null IV to blockcipher. + - Shared library is now linked dynamically, with shared object name and version. + - Tested on Alpha Linux. + - Tested on Alpha FreeBSD. + - Added support for Compaq Alpha Tru64 Unix. + - Added initial support for QNX. + +1.1.0: + - Added glue for interfacing from BeeCrypt Java Cryptography Provider. + - Changed blockcipher struct to support interfacing with Java. + - Added better blockcipher IV handling. + - Multi-pass block processing is now possible with blockEncrypt/blockDecrypt. + - Updated config.sub and config.guess to latest version from sources.redhat.com + - Changed opening of entropy devices to blocking read-only mode instead of non-blocking read-write. + - Added win32 'wincrypt' entropy source. + - Added win32 'console' entropy source. + - Added FreeBSD support. + - Added PowerPC assembler optimized multiprecision subtraction routines. + - Added initial ia64 support. + - Added initial Darwin support (everything compiles, but the shared library doesn't build yet). + +1.0.2: + - Fixed Windows 2000 entropy bug; instead of using the first waveIn device, entropy now uses WAVE_MAPPER. + - Added sparcv9 mp32addsqrtrc GNU assembler routine. + - Added more hashFunctionContext and keyedHashFunctionContext functions. + +1.0.1: + - Added a sliding window modular exponentiation, about 30% faster than left-to-right exponentiation. + - Fixed bugs in fips180opt.gas.i586.s (Linux SHA-1 assembler code for Pentium/Pentium Pro) - the Windows/Metrowerks version was okay. + +1.0.0: + - Added Win32 support; compiled as DLL with MetroWerks CodeWarrior Pro 5, it runs fine on Windows 95, 98, NT 4.0 (if you have a soundcard with a microphone port). Note that there is a know issue on Windows 2000, see BUGS. + - Global code overhaul to support Win32 + - Added more assembler routines, including SHA-1 for Pentium Pro (60% faster) + - Added cleanup function to randomGenerator + - Added missing functions in endianness.c + - Fixed bug in entropy.c where devices might stay open + - Eliminated mutex.h include file; it was more clear to do everything conditionally than to expand the macros in this file to encompass the Win32 API calls. + +0.9.5: + - Added PowerPC assembler optimization for multiprecision integers, 80% faster on our PowerMac 7200/90 + - Fixed /dev/random entropy provider + - Changed name SHA1 to SHA-1 in fips180 for consistency + +0.9.4a: + - Added missing file 'blowfishopt.o' + +0.9.4: + - Changes to configure script, to distinguish between different processors of the x86 family + - Changes to blowfish code, 586/686 assembler optimization added, 30% faster on Pentium/PentiumPro + - Changes to blowfish code, eliminated static blowfishSetupEncrypt; incorporated into regular encrypt + - Changes to Makefile to selectively use blowfish assember code, depending on cpu type + - Added missing routines 'mp32bzero' and 'mp32bnpowmod' to mp32barrett.c + - Fixed 'const register' to 'register const' in mp32.c + - Minor fixes in included header files + +0.9.3: + - Initial public release diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README new file mode 100755 index 0000000000..d875372c39 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README @@ -0,0 +1,143 @@ +Welcome to the BeeCrypt crypto library! + +Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V. +Copyright (c) 2002, 2003, Bob Deblier (for certain parts) + +Author: Bob Deblier <bob.deblier@pandora.be> + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library 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 +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +For the specifics of this license, see file 'COPYING.LIB', included in +this distribution. + + + +Welcome to version 3.0.0 of BeeCrypt: + +AES support has been added, and the library has been thoroughly debugged, +with the addition of unit tests. Once you've built the library, you can +verify the correct functioning with 'make check'. + +Multi-precision integer routines should now perform dramatically better +an 64-bit processors, especially Alpha and Itanium. + +Benchmarks can be obtained with 'make bench'. + +As usual, your comments are welcome. + + + +About BeeCrypt: + +This library is an ongoing project of Virtual Unlimited B.V. Its goal is +to provide strong and fast cryptography for use by our products, but +we're not limiting the use to that. We're releasing it under the LGPL +license, because we feel that cryptography should be open to inspection +by everybody, and available for use by everybody to safeguard privacy. + +Note that depending on where you are, the use of cryptography may be +limited or forbidden by law. Before using this library, make sure you +are legally entitled to do so. + + +For more on Virtual Unlimited B.V. and our products please consult our +website: http://www.virtualunlimited.com/ + + +<plug> +Most of the algorithms are implemented from reliable sources such as: + +"Handbook of Applied Cryptography" + Alfred J. Menezes, Paul C. van Oorschot, Scott A. Vanstone + CRC Press + +"Applied Cryptography", second edition + Bruce Schneier + Wiley + + +For crypto enthusiasts these books are invaluable background material. + +IEEE P1363 "Standard Specifications for Public Key Cryptography" is a +very interesting draft standard, which we will try to comply with. +</plug> + +The structures in the library are geared towards exchange with Java +and its security and cryptography classes. This library can also be +accessed from Java by installing BeeCrypt for Java, a JCE 1.2 crypto +provider and the counterpart of this library. + + +Included in the library are: + - entropy sources for initializing pseudo-random generators + - pseudo-random generators: FIPS-186, Mersenne Twister + - block ciphers: AES, Blowfish + - hash functions: MD5, SHA-1, SHA-256 + - keyed hash functions: HMAC-MD5, HMAC-SHA-1, HMAC-SHA-256 + - multi-precision integer library, with assembler-optimized routines + for several processors + - probabilistic primality testing, with optimized small prime trial + division + - discrete logarithm parameter generation over a prime field + - Diffie-Hellman key agreement + - DSA signature scheme + - ElGamal signature scheme (two variants) + - RSA keypair generation with chinese remainder theorem variables + - RSA public & private key operations + - DHAES encryption scheme + +Planned for the near future are: + - compliance with and compliance statements for IEEE P1363 + - more blockciphers (Twofish, ... ) + - more hash functions (RIPEMD-160, SHA-384, SHA-512, HAVAL, Tiger) + - RSA signatures as specified by RFC-2440. + - Elliptic Curves (ECDSA, ... ) + - more blockcipher modes (OFB, ... ) + +The library has been tested on the following platforms: + - AIX 5.1 ppc + - AIX 5.1 ppc64 + - Darwin 6.5 (a.k.a. MacOS X 10.2) + - FreeBSD 4.0 alpha + - FreeBSD 4.0, 4.2 x86 + - Linux glibc 2.x alpha + - Linux glibc 2.x arm + - Linux glibc 2.x ia64 + - Linux glibc 2.x ppc + - Linux glibc 2.x sparc + - Linux glibc 2.x x86 + - Solaris 2.6/2.7/2.8/2.9 sparc (with Forte or gnu compilers) + - Solaris 2.7/2.8 x86 (with Forte or GNU compilers) + - Tru64 Unix alpha + - Win32 (Windows 95, 98, NT 4.0, 2000, XP) + +The library is currently in the process of being ported to: + - Cygwin (Can't seem to get the DLL to build properly with the current + version of the autotools) + - HP/UX is a pain in the backside; I'll try getting it working, but the + configure script doesn't seem capable of properly detecting gettimeofday. + +For more information, refer to the HTML documentation in the docs directory. + +If you want to report bugs, make suggestions, contribute fixes or +enhancements, please see the beecrypt-specific website: + +http://sourceforge.net/projects/beecrypt + +or contact me at mailto:bob.deblier@pandora.be + +Sincerely, + +Bob Deblier diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL new file mode 100755 index 0000000000..2131f87ce2 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.DLL @@ -0,0 +1,37 @@ +File beetest.exe is a compiled version of the test program included in +the source distribution, which you can find on our website: +http://beecrypt.virtualunlimited.com/ + +To run, it needs file beecrypt.dll present in the same directory. + +For Developers: + +Files beecrypt.dll and beecrypt.lib are a pre-compiled version of the +BeeCrypt library for Pentium Pro processors. + +If you want to develop applications with this library, you'll also need +the header files, included in the source distribution (see higher). + +Please make sure you respect the term of the license under which the +BeeCrypt library is released: + +Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V. + +Author: Bob Deblier <bob@virtualunlimited.com> + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library 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 +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +For the specifics of this license, see file 'COPYING', included in this +distribution. diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32 b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32 new file mode 100755 index 0000000000..411116fea2 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/README.WIN32 @@ -0,0 +1,43 @@ +This file contains information on how to build and use the BeeCrypt DLL on +Win32 platforms. + +The platform of preference is currently MicroSoft Visual C++ 6.0, but +Metrowerks CodeWarrior is also still supported. + +To be able to use the assembler files with Visual C++, you need to have the +Visual C++ 6.0 Processor Pack installed. It can be found at: + +http://msdn.microsoft.com/vstudio/downloads/ppack/default.asp + +To be able to use the assembler files with Metrowerks CodeWarrior, you will +need to install an unsupported (but working for the included files) assembler +plug-in, which can be found on the CodeWarrior download page. + +To build the java glue into the DLL, you should also have Sun's JDK 1.3, +including the JNI headers, installed. + +Make sure all Visual C++ tools can be found on the path, i.e.: + +cl.exe (the compiler) +ml.exe (the assembler) +link.exe (the linker) +nmake.exe (the make utility) + +For convenience, copy file 'Makefile.mak' to 'Makefile' and adjust paths as +required. The Makefile assumes you will be building in support for java. +If this is not the case, you will have to adjust the Makefile, which shouldn't +be too difficult. + +Next, run 'nmake' and the library and the test program will be built. + +Once running, you can use any of three entropy source available on this +platform, in order of preference: + +wavein (uses noise on the soundcard microphone port) +console (uses keyboard clicks with a high resolution timer) +wincrypt (uses random data generated by the Windows CryptAPI) + +To enable a specific entropy device, set variable BEECRYPT_ENTROPY to any of +these three values; if not specified, the library will use 'wavein' as default. + +In the future, additional sources of entropy on this platform will be made available. diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h new file mode 100755 index 0000000000..f5ef7ff04a --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/api.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2001, 2002, 2004 Beeyond Software Holding BV + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file api.h + * \brief BeeCrypt API, portability headers. + * \author Bob Deblier <bob.deblier@pandora.be> + */ + +#ifndef _BEECRYPT_API_H +#define _BEECRYPT_API_H + +#if defined(_WIN32) && !defined(WIN32) +# define WIN32 1 +#endif + +#if WIN32 +# if !__CYGWIN32__ +# include "beecrypt/win.h" +# else +# include "beecrypt/gnu.h" +# endif +# ifdef BEECRYPT_DLL_EXPORT +# define BEECRYPTAPI //__declspec(dllexport) +# else +# define BEECRYPTAPI //__declspec(dllimport) +# endif +# ifdef BEECRYPT_CXX_DLL_EXPORT +# define BEECRYPTCXXAPI //__declspec(dllexport) +# define BEECRYPTCXXTEMPLATE +# else +# define BEECRYPTCXXAPI //__declspec(dllimport) +# define BEECRYPTCXXTEMPLATE extern +# endif +#else +# include "beecrypt/gnu.h" +# define BEECRYPTAPI +# define BEECRYPTCXXAPI +#endif + +#ifndef ROTL32 +# define ROTL32(x, s) (((x) << (s)) | ((x) >> (32 - (s)))) +#endif +#ifndef ROTR32 +# define ROTR32(x, s) (((x) >> (s)) | ((x) << (32 - (s)))) +#endif +#ifndef ROTR64 +# define ROTR64(x, s) (((x) >> (s)) | ((x) << (64 - (s)))) +#endif + +typedef uint8_t byte; + +typedef int8_t javabyte; +typedef int16_t javashort; +typedef int32_t javaint; +typedef int64_t javalong; + +typedef uint16_t javachar; + +#if (MP_WBITS == 64) +typedef uint64_t mpw; +typedef uint32_t mphw; +#elif (MP_WBITS == 32) +# if HAVE_UINT64_T +# define HAVE_MPDW 1 +typedef uint64_t mpdw; +# endif +typedef uint32_t mpw; +typedef uint16_t mphw; +#else +# error +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h new file mode 100755 index 0000000000..a4c8780d03 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/beecrypt.h @@ -0,0 +1,799 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file beecrypt.h + * \brief BeeCrypt API, headers. + * + * These API functions provide an abstract way for using most of + * the various algorithms implemented by the library. + * + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup ES_m PRNG_m HASH_m HMAC_m BC_m + */ + +#ifndef _BEECRYPT_H +#define _BEECRYPT_H + +#include "beecrypt/api.h" + +#include "beecrypt/memchunk.h" +#include "beecrypt/mpnumber.h" + +/* + * Entropy Sources + */ + +/*!\typedef entropyNext + * \brief Prototype definition for an entropy-generating function. + * \ingroup ES_m + */ +typedef int (*entropyNext)(byte*, size_t); + +/*!\brief This struct holds information and pointers to code specific to each + * source of entropy. + * \ingroup ES_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI entropySource +#else +struct _entropySource +#endif +{ + /*!\var name + * \brief The entropy source's name. + */ + const char* name; + /*!\var next + * \brief Points to the function which produces the entropy. + */ + const entropyNext next; +}; + +#ifndef __cplusplus +typedef struct _entropySource entropySource; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\fn int entropySourceCount() + * \brief This function returns the number of entropy sources implemented by + * the library. + * \return The number of implemented entropy sources. + */ +BEECRYPTAPI +int entropySourceCount(void); + +/*!\fn const entropySource* entropySourceGet(int n) + * \brief This function returns the \a n -th entropy source implemented by + * the library. + * \param n Index of the requested entropy source; legal values are 0 + * through entropySourceCount() - 1. + * \return A pointer to an entropy source or null, if the index was out of + * range. + */ +BEECRYPTAPI +const entropySource* entropySourceGet(int n); + +/*!\fn const entropySource* entropySourceFind(const char* name) + * \brief This function returns the entropy source specified by the given name. + * \param name Name of the requested entropy source. + * \return A pointer to an entropy source or null, if the name wasn't found. + */ +BEECRYPTAPI +const entropySource* entropySourceFind(const char* name); + +/*!\fn const entropySource* entropySourceDefault() + * \brief This functions returns the default entropy source; the default value + * can be specified by setting environment variable BEECRYPT_ENTROPY. + * \return A pointer to an entropy source or null, in case an error occured. + */ +BEECRYPTAPI +const entropySource* entropySourceDefault(void); + +/*!\fn int entropyGatherNext(byte* data, size_t size) + * \brief This function gathers \a size bytes of entropy into \a data. + * + * Unless environment variable BEECRYPT_ENTROPY is set, this function will + * try each successive entropy source to gather up the requested amount. + * + * \param data Points to where the entropy should be stored. + * \param size Indicates how many bytes of entropy should be gathered. + * \retval 0 On success. + * \retval -1 On failure. + */ +BEECRYPTAPI +int entropyGatherNext(byte*, size_t); + +#ifdef __cplusplus +} +#endif + +/* + * Pseudo-random Number Generators + */ + +typedef void randomGeneratorParam; + +typedef int (*randomGeneratorSetup )(randomGeneratorParam*); +typedef int (*randomGeneratorSeed )(randomGeneratorParam*, const byte*, size_t); +typedef int (*randomGeneratorNext )(randomGeneratorParam*, byte*, size_t); +typedef int (*randomGeneratorCleanup)(randomGeneratorParam*); + +/* + * The struct 'randomGenerator' holds information and pointers to code specific + * to each random generator. Each specific random generator MUST be written to + * be multithread safe. + * + * WARNING: each randomGenerator, when used in cryptographic applications, MUST + * be guaranteed to be of suitable quality and strength (i.e. don't use the + * random() function found in most UN*X-es). + * + * Multiple instances of each randomGenerator can be used (even concurrently), + * provided they each use their own randomGeneratorParam parameters, a chunk + * of memory which must be at least as large as indicated by the paramsize + * field. + * + */ + +/*!\brief This struct holds information and pointers to code specific to each + * pseudo-random number generator. + * \ingroup PRNG_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI randomGenerator +#else +struct _randomGenerator +#endif +{ + /*!\var name + * \brief The random generator's name. + */ + const char* name; + /*!\var paramsize + * \brief The size of the random generator's parameters. + * \note The implementor should set this by using sizeof(<struct holding + * random generator's parameters>). + */ + const size_t paramsize; + /*!\var setup + * \brief Points to the setup function. + */ + const randomGeneratorSetup setup; + /*!\var seed + * \brief Points to the seeding function. + */ + const randomGeneratorSeed seed; + /*!\var seed + * \brief Points to the function which generates the random data. + */ + const randomGeneratorNext next; + /*!\var seed + * \brief Points to the cleanup function. + */ + const randomGeneratorCleanup cleanup; +}; + +#ifndef __cplusplus +typedef struct _randomGenerator randomGenerator; +#endif + +/* + * You can use the following functions to find random generators implemented by + * the library: + * + * randomGeneratorCount returns the number of generators available. + * + * randomGeneratorGet returns the random generator with a given index (starting + * at zero, up to randomGeneratorCount() - 1), or NULL if the index was out of + * bounds. + * + * randomGeneratorFind returns the random generator with the given name, or + * NULL if no random generator exists with that name. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int randomGeneratorCount(void); +BEECRYPTAPI +const randomGenerator* randomGeneratorGet(int); +BEECRYPTAPI +const randomGenerator* randomGeneratorFind(const char*); +BEECRYPTAPI +const randomGenerator* randomGeneratorDefault(void); + +#ifdef __cplusplus +} +#endif + +/* + * The struct 'randomGeneratorContext' is used to contain both the functional + * part (the randomGenerator), and its parameters. + */ + +#ifdef __cplusplus +struct BEECRYPTAPI randomGeneratorContext +#else +struct _randomGeneratorContext +#endif +{ + const randomGenerator* rng; + randomGeneratorParam* param; + + #ifdef __cplusplus + randomGeneratorContext(); + randomGeneratorContext(const randomGenerator*); + ~randomGeneratorContext(); + #endif +}; + +#ifndef __cplusplus +typedef struct _randomGeneratorContext randomGeneratorContext; +#endif + +/* + * The following functions can be used to initialize and free a + * randomGeneratorContext. Initializing will allocate a buffer of the size + * required by the randomGenerator, freeing will deallocate that buffer. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int randomGeneratorContextInit(randomGeneratorContext*, const randomGenerator*); +BEECRYPTAPI +int randomGeneratorContextFree(randomGeneratorContext*); +BEECRYPTAPI +int randomGeneratorContextNext(randomGeneratorContext*, byte*, size_t); +BEECRYPTAPI +int randomGeneratorContextSeed(randomGeneratorContext*, const byte*, size_t); + +#ifdef __cplusplus +} +#endif + +/* + * Hash Functions + */ + +/*!typedef void hashFunctionParam + * \ingroup HASH_m + */ +typedef void hashFunctionParam; + +typedef int (*hashFunctionReset )(hashFunctionParam*); +typedef int (*hashFunctionUpdate)(hashFunctionParam*, const byte*, size_t); +typedef int (*hashFunctionDigest)(hashFunctionParam*, byte*); + +/* + * The struct 'hashFunction' holds information and pointers to code specific + * to each hash function. Specific hash functions MAY be written to be + * multithread-safe. + * + * NOTE: data MUST have a size (in bytes) of at least 'digestsize' as described + * in the hashFunction struct. + * NOTE: for safety reasons, after calling digest, each specific implementation + * MUST reset itself so that previous values in the parameters are erased. + */ +#ifdef __cplusplus +struct BEECRYPTAPI hashFunction +#else +struct _hashFunction +#endif +{ + const char* name; + const size_t paramsize; /* in bytes */ + const size_t blocksize; /* in bytes */ + const size_t digestsize; /* in bytes */ + const hashFunctionReset reset; + const hashFunctionUpdate update; + const hashFunctionDigest digest; +}; + +#ifndef __cplusplus +typedef struct _hashFunction hashFunction; +#endif + +/* + * You can use the following functions to find hash functions implemented by + * the library: + * + * hashFunctionCount returns the number of hash functions available. + * + * hashFunctionGet returns the hash function with a given index (starting + * at zero, up to hashFunctionCount() - 1), or NULL if the index was out of + * bounds. + * + * hashFunctionFind returns the hash function with the given name, or + * NULL if no hash function exists with that name. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int hashFunctionCount(void); +BEECRYPTAPI +const hashFunction* hashFunctionGet(int); +BEECRYPTAPI +const hashFunction* hashFunctionFind(const char*); +BEECRYPTAPI +const hashFunction* hashFunctionDefault(void); + +#ifdef __cplusplus +} +#endif + +/* + * The struct 'hashFunctionContext' is used to contain both the functional + * part (the hashFunction), and its parameters. + */ +#ifdef __cplusplus +struct BEECRYPTAPI hashFunctionContext +#else +struct _hashFunctionContext +#endif +{ + const hashFunction* algo; + hashFunctionParam* param; + + #ifdef __cplusplus + hashFunctionContext(); + hashFunctionContext(const hashFunction*); + ~hashFunctionContext(); + #endif +}; + +#ifndef __cplusplus +typedef struct _hashFunctionContext hashFunctionContext; +#endif + +/* + * The following functions can be used to initialize and free a + * hashFunctionContext. Initializing will allocate a buffer of the size + * required by the hashFunction, freeing will deallocate that buffer. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int hashFunctionContextInit(hashFunctionContext*, const hashFunction*); +BEECRYPTAPI +int hashFunctionContextFree(hashFunctionContext*); +BEECRYPTAPI +int hashFunctionContextReset(hashFunctionContext*); +BEECRYPTAPI +int hashFunctionContextUpdate(hashFunctionContext*, const byte*, size_t); +BEECRYPTAPI +int hashFunctionContextUpdateMC(hashFunctionContext*, const memchunk*); +BEECRYPTAPI +int hashFunctionContextUpdateMP(hashFunctionContext*, const mpnumber*); +BEECRYPTAPI +int hashFunctionContextDigest(hashFunctionContext*, byte*); +BEECRYPTAPI +int hashFunctionContextDigestMP(hashFunctionContext*, mpnumber*); +BEECRYPTAPI +int hashFunctionContextDigestMatch(hashFunctionContext*, const mpnumber*); + +#ifdef __cplusplus +} +#endif + +/* + * Keyed Hash Functions, a.k.a. Message Authentication Codes + */ + +/*!\typedef void keyedHashFunctionParam + * \ingroup HMAC_m + */ +typedef void keyedHashFunctionParam; + +typedef int (*keyedHashFunctionSetup )(keyedHashFunctionParam*, const byte*, size_t); +typedef int (*keyedHashFunctionReset )(keyedHashFunctionParam*); +typedef int (*keyedHashFunctionUpdate )(keyedHashFunctionParam*, const byte*, size_t); +typedef int (*keyedHashFunctionDigest )(keyedHashFunctionParam*, byte*); + +/* + * The struct 'keyedHashFunction' holds information and pointers to code + * specific to each keyed hash function. Specific keyed hash functions MAY be + * written to be multithread-safe. + * + * The struct field 'keybitsmin' contains the minimum number of bits a key + * must contains, 'keybitsmax' the maximum number of bits a key may contain, + * 'keybitsinc', the increment in bits that may be used between min and max. + * + * NOTE: data must be at least have a bytesize of 'digestsize' as described + * in the keyedHashFunction struct. + * NOTE: for safety reasons, after calling digest, each specific implementation + * MUST reset itself so that previous values in the parameters are erased. + */ +#ifdef __cplusplus +struct BEECRYPTAPI keyedHashFunction +#else +struct _keyedHashFunction +#endif +{ + const char* name; + const size_t paramsize; /* in bytes */ + const size_t blocksize; /* in bytes */ + const size_t digestsize; /* in bytes */ + const size_t keybitsmin; /* in bits */ + const size_t keybitsmax; /* in bits */ + const size_t keybitsinc; /* in bits */ + const keyedHashFunctionSetup setup; + const keyedHashFunctionReset reset; + const keyedHashFunctionUpdate update; + const keyedHashFunctionDigest digest; +}; + +#ifndef __cplusplus +typedef struct _keyedHashFunction keyedHashFunction; +#endif + +/* + * You can use the following functions to find keyed hash functions implemented + * by the library: + * + * keyedHashFunctionCount returns the number of keyed hash functions available. + * + * keyedHashFunctionGet returns the keyed hash function with a given index + * (starting at zero, up to keyedHashFunctionCount() - 1), or NULL if the index + * was out of bounds. + * + * keyedHashFunctionFind returns the keyed hash function with the given name, + * or NULL if no keyed hash function exists with that name. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int keyedHashFunctionCount(void); +BEECRYPTAPI +const keyedHashFunction* keyedHashFunctionGet(int); +BEECRYPTAPI +const keyedHashFunction* keyedHashFunctionFind(const char*); +BEECRYPTAPI +const keyedHashFunction* keyedHashFunctionDefault(void); + +#ifdef __cplusplus +} +#endif + +/* + * The struct 'keyedHashFunctionContext' is used to contain both the functional + * part (the keyedHashFunction), and its parameters. + */ +#ifdef __cplusplus +struct BEECRYPTAPI keyedHashFunctionContext +#else +struct _keyedHashFunctionContext +#endif +{ + const keyedHashFunction* algo; + keyedHashFunctionParam* param; + + #ifdef __cplusplus + keyedHashFunctionContext(); + keyedHashFunctionContext(const keyedHashFunction*); + ~keyedHashFunctionContext(); + #endif +}; + +#ifndef __cplusplus +typedef struct _keyedHashFunctionContext keyedHashFunctionContext; +#endif + +/* + * The following functions can be used to initialize and free a + * keyedHashFunctionContext. Initializing will allocate a buffer of the size + * required by the keyedHashFunction, freeing will deallocate that buffer. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int keyedHashFunctionContextInit(keyedHashFunctionContext*, const keyedHashFunction*); +BEECRYPTAPI +int keyedHashFunctionContextFree(keyedHashFunctionContext*); +BEECRYPTAPI +int keyedHashFunctionContextSetup(keyedHashFunctionContext*, const byte*, size_t); +BEECRYPTAPI +int keyedHashFunctionContextReset(keyedHashFunctionContext*); +BEECRYPTAPI +int keyedHashFunctionContextUpdate(keyedHashFunctionContext*, const byte*, size_t); +BEECRYPTAPI +int keyedHashFunctionContextUpdateMC(keyedHashFunctionContext*, const memchunk*); +BEECRYPTAPI +int keyedHashFunctionContextUpdateMP(keyedHashFunctionContext*, const mpnumber*); +BEECRYPTAPI +int keyedHashFunctionContextDigest(keyedHashFunctionContext*, byte*); +BEECRYPTAPI +int keyedHashFunctionContextDigestMP(keyedHashFunctionContext*, mpnumber*); +BEECRYPTAPI +int keyedHashFunctionContextDigestMatch(keyedHashFunctionContext*, const mpnumber*); + +#ifdef __cplusplus +} +#endif + +/* + * Block ciphers + */ + +/*!\enum cipherOperation + * \brief Specifies whether to perform encryption or decryption. + * \ingroup BC_m + */ +typedef enum +{ + NOCRYPT, + ENCRYPT, + DECRYPT +} cipherOperation; + +/*!\typedef void blockCipherParam + * \brief Placeholder type definition for blockcipher parameters. + * \sa aesParam, blowfishParam. + * \ingroup BC_m + */ +typedef void blockCipherParam; + +/*!\brief Prototype definition for a setup function. + * \ingroup BC_m + */ +typedef int (*blockCipherSetup )(blockCipherParam*, const byte*, size_t, cipherOperation); + +/*!\typedef int (*blockCipherSetIV)(blockCipherParam* bp, const byte* iv) + * \brief Prototype definition for an initialization vector setup function. + * \param bp The blockcipher's parameters. + * \param iv The blockciphers' IV value. + * \note iv length must be equal to the cipher's block size. + * \retval 0 on success. + * \retval -1 on failure. + * \ingroup BC_m + */ +typedef int (*blockCipherSetIV )(blockCipherParam*, const byte*); + +/*!\typedef int (*blockCipherRawcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src) + * \brief Prototype for a \e raw encryption or decryption function. + * \param bp The blockcipher's parameters. + * \param dst The ciphertext address; must be aligned on 32-bit boundary. + * \param src The cleartext address; must be aligned on 32-bit boundary. + * \retval 0 on success. + * \retval -1 on failure. + * \ingroup BC_m + */ +typedef int (*blockCipherRawcrypt)(blockCipherParam*, uint32_t*, const uint32_t*); + +/*!\typedef int (*blockCipherModcrypt)(blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) + * \brief Prototype for a \e encryption or decryption function which operates + * on multiple blocks in a certain mode. + * \param bp The blockcipher's parameters. + * \param dst The ciphertext address; must be aligned on 32-bit boundary. + * \param src The cleartext address; must be aligned on 32-bit boundary. + * \param nblocks The number of blocks to process. + * \retval 0 on success. + * \retval -1 on failure. + * \ingroup BC_m + */ +typedef int (*blockCipherModcrypt)(blockCipherParam*, uint32_t*, const uint32_t*, unsigned int); + +typedef uint32_t* (*blockCipherFeedback)(blockCipherParam*); + +typedef struct +{ + const blockCipherRawcrypt encrypt; + const blockCipherRawcrypt decrypt; +} blockCipherRaw; + +typedef struct +{ + const blockCipherModcrypt encrypt; + const blockCipherModcrypt decrypt; +} blockCipherMode; + +/*!\brief Holds information and pointers to code specific to each cipher. + * + * Specific block ciphers \e may be written to be multithread-safe. + * + * \ingroup BC_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI blockCipher +#else +struct _blockCipher +#endif +{ + /*!\var name + * \brief The blockcipher's name. + */ + const char* name; + /*!\var paramsize + * \brief The size of the parameters required by this cipher, in bytes. + */ + const size_t paramsize; + /*!\var blocksize + * \brief The size of one block of data, in bytes. + */ + const size_t blocksize; + /*!\var keybitsmin + * \brief The minimum number of key bits. + */ + const size_t keybitsmin; + /*!\var keybitsmax + * \brief The maximum number of key bits. + */ + const size_t keybitsmax; + /*!\var keybitsinc + * \brief The allowed increment in key bits between min and max. + * \see keybitsmin and keybitsmax. + */ + const size_t keybitsinc; + /*!\var setup + * \brief Pointer to the cipher's setup function. + */ + const blockCipherSetup setup; + /*!\var setiv + * \brief Pointer to the cipher's initialization vector setup function. + */ + const blockCipherSetIV setiv; + /*!\var raw + * \brief The cipher's raw functions. + */ + const blockCipherRaw raw; + /*!\var ecb + * \brief The cipher's ECB functions. + */ + const blockCipherMode ecb; + const blockCipherMode cbc; + /*!\var getfb + * \brief Pointer to the cipher's feedback-returning function. + */ + const blockCipherFeedback getfb; +}; + +#ifndef __cplusplus +typedef struct _blockCipher blockCipher; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\fn int blockCipherCount() + * \brief This function returns the number of blockciphers implemented + * by the library. + * \return The number of implemented blockciphers. + */ +BEECRYPTAPI +int blockCipherCount(void); + +/*!\fn const blockCipher* blockCipherGet(int n) + * \brief This function returns the \a n -th blockcipher implemented by + * the library. + * \param n Index of the requested blockcipher; legal values are 0 + * through blockCipherCount() - 1. + * \return A pointer to a blockcipher or null, if the index was out of + * range. + */ +BEECRYPTAPI +const blockCipher* blockCipherGet(int); + +/*!\fn const blockCipher* blockCipherFind(const char* name) + * \brief This function returns the blockcipher specified by the given name. + * \param name Name of the requested blockcipher. + * \return A pointer to a blockcipher or null, if the name wasn't found. + */ +BEECRYPTAPI +const blockCipher* blockCipherFind(const char*); + +/*!\fn const blockCipher* blockCipherDefault() + * \brief This functions returns the default blockcipher; the default value + * can be specified by setting environment variable BEECRYPT_CIPHER. + * \return A pointer to a blockcipher or null, in case an error occured. + */ +BEECRYPTAPI +const blockCipher* blockCipherDefault(void); + +#ifdef __cplusplus +} +#endif + +/*!\brief Holds a pointer to a blockcipher as well as its parameters. + * \warning A context can be used by only one thread at the same time. + * \ingroup BC_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI blockCipherContext +#else +struct _blockCipherContext +#endif +{ + /*!\var algo + * \brief Pointer to a blockCipher. + */ + const blockCipher* algo; + /*!\var param + * \brief Pointer to the parameters used by algo. + */ + blockCipherParam* param; + /*!\var op + */ + cipherOperation op; + + #ifdef __cplusplus + blockCipherContext(); + blockCipherContext(const blockCipher*); + ~blockCipherContext(); + #endif +}; + +#ifndef __cplusplus +typedef struct _blockCipherContext blockCipherContext; +#endif + +/* + * The following functions can be used to initialize and free a + * blockCipherContext. Initializing will allocate a buffer of the size + * required by the blockCipher, freeing will deallocate that buffer. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +int blockCipherContextInit(blockCipherContext*, const blockCipher*); + +BEECRYPTAPI +int blockCipherContextSetup(blockCipherContext*, const byte*, size_t, cipherOperation); + +BEECRYPTAPI +int blockCipherContextSetIV(blockCipherContext*, const byte*); + +BEECRYPTAPI +int blockCipherContextFree(blockCipherContext*); + +BEECRYPTAPI +int blockCipherContextECB(blockCipherContext*, uint32_t*, const uint32_t*, int); + +BEECRYPTAPI +int blockCipherContextCBC(blockCipherContext*, uint32_t*, const uint32_t*, int); + +BEECRYPTAPI +int blockCipherContextValidKeylen(blockCipherContext*, size_t); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c new file mode 100755 index 0000000000..cfccd43337 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.c @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file blockmode.c + * \brief Blockcipher operation modes. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup BC_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/blockmode.h" + +int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) +{ + register const unsigned int blockwords = bc->blocksize >> 2; + + while (nblocks > 0) + { + bc->raw.encrypt(bp, dst, src); + + dst += blockwords; + src += blockwords; + + nblocks--; + } + + return 0; +} + +int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) +{ + register const unsigned int blockwords = bc->blocksize >> 2; + + while (nblocks > 0) + { + bc->raw.decrypt(bp, dst, src); + + dst += blockwords; + src += blockwords; + + nblocks--; + } + + return 0; +} + +int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) +{ + register const unsigned int blockwords = bc->blocksize >> 2; + register uint32_t* fdback = bc->getfb(bp); + + if (nblocks > 0) + { + register unsigned int i; + + for (i = 0; i < blockwords; i++) + dst[i] = src[i] ^ fdback[i]; + + bc->raw.encrypt(bp, dst, dst); + + nblocks--; + + while (nblocks > 0) + { + for (i = 0; i < blockwords; i++) + dst[i+blockwords] = src[i+blockwords] ^ dst[i]; + + dst += blockwords; + + bc->raw.encrypt(bp, dst, dst); + + src += blockwords; + + nblocks--; + } + + for (i = 0; i < blockwords; i++) + fdback[i] = dst[i]; + } + + return 0; +} + +int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) +{ + register const unsigned int blockwords = bc->blocksize >> 2; + register uint32_t* fdback = bc->getfb(bp); + register uint32_t* buf = (uint32_t*) malloc(blockwords * sizeof(uint32_t)); + + if (buf) + { + while (nblocks > 0) + { + register uint32_t tmp; + register unsigned int i; + + bc->raw.decrypt(bp, buf, src); + + for (i = 0; i < blockwords; i++) + { + tmp = src[i]; + dst[i] = buf[i] ^ fdback[i]; + fdback[i] = tmp; + } + + dst += blockwords; + src += blockwords; + + nblocks--; + } + free(buf); + return 0; + } + + return -1; +} diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h new file mode 100755 index 0000000000..4f21b81f65 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blockmode.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file blockmode.h + * \brief Blockcipher operation modes. + * \todo Additional modes, such as CFB and OFB. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup BC_m + */ + +#ifndef _BLOCKMODE_H +#define _BLOCKMODE_H + +#include "beecrypt/beecrypt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\fn int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) + * \brief This function encrypts a number of data blocks in Electronic Code + * Book mode. + * \param bc The blockcipher. + * \param bp The cipher's parameter block. + * \param dst The ciphertext data; should be aligned on a 32-bit boundary. + * \param src The cleartext data; should be aligned on a 32-bit boundary. + * \param nblocks The number of blocks to be encrypted. + * \retval 0 on success. + */ +BEECRYPTAPI +int blockEncryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks); + +/*!\fn int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) + * \brief This function decrypts a number of data blocks in Electronic Code + * Book mode. + * \param bc The blockcipher. + * \param bp The cipher's parameter block. + * \param dst The cleartext data; should be aligned on a 32-bit boundary. + * \param src The ciphertext data; should be aligned on a 32-bit boundary. + * \param nblocks The number of blocks to be decrypted. + * \retval 0 on success. + */ +BEECRYPTAPI +int blockDecryptECB(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks); + +/*!\fn int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) + * \brief This function encrypts a number of data blocks in Cipher Block + * Chaining mode. + * \param bc The blockcipher. + * \param bp The cipher's parameter block. + * \param dst The ciphertext data; should be aligned on a 32-bit boundary. + * \param src The cleartext data; should be aligned on a 32-bit boundary. + * \param nblocks The number of blocks to be encrypted. + * \retval 0 on success. + */ +BEECRYPTAPI +int blockEncryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks); + +/*!\fn int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks) + * \brief This function decrypts a number of data blocks in Cipher Block + * Chaining mode. + * \param bc The blockcipher. + * \param bp The cipher's parameter block. + * \param dst The cleartext data; should be aligned on a 32-bit boundary. + * \param src The ciphertext data; should be aligned on a 32-bit boundary. + * \param nblocks The number of blocks to be decrypted. + * \retval 0 on success. + */ +BEECRYPTAPI +int blockDecryptCBC(const blockCipher* bc, blockCipherParam* bp, uint32_t* dst, const uint32_t* src, unsigned int nblocks); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c new file mode 100755 index 0000000000..a8b801e6ec --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.c @@ -0,0 +1,509 @@ +/* + * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file blowfish.c + * \brief Blowfish block cipher. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup BC_m BC_blowfish_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/blowfish.h" + +#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H +# include <endian.h> +#endif + +#include "beecrypt/endianness.h" + +#ifdef ASM_BLOWFISHENCRYPTECB +extern int blowfishEncryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int); +#endif + +#ifdef ASM_BLOWFISHDECRYPTECB +extern int blowfishDecryptECB(blowfishparam*, uint32_t*, const uint32_t*, unsigned int); +#endif + +static uint32_t _bf_p[BLOWFISHPSIZE] = { + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b +}; + +static uint32_t _bf_s[1024] = { + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 +}; + +#define EROUND(l,r) l ^= *(p++); r ^= ((s[((l>>24)&0xff)+0x000]+s[((l>>16)&0xff)+0x100])^s[((l>>8)&0xff)+0x200])+s[((l>>0)&0xff)+0x300] +#define DROUND(l,r) l ^= *(p--); r ^= ((s[((l>>24)&0xff)+0x000]+s[((l>>16)&0xff)+0x100])^s[((l>>8)&0xff)+0x200])+s[((l>>0)&0xff)+0x300] + +const blockCipher blowfish = { + "Blowfish", + sizeof(blowfishParam), + 8, + 64, + 448, + 32, + (blockCipherSetup) blowfishSetup, + (blockCipherSetIV) blowfishSetIV, + /* raw */ + { + (blockCipherRawcrypt) blowfishEncrypt, + (blockCipherRawcrypt) blowfishDecrypt + }, + /* ecb */ + { + #ifdef AES_BLOWFISHENCRYPTECB + (blockCipherModcrypt) blowfishEncryptECB, + #else + (blockCipherModcrypt) 0, + #endif + #ifdef AES_BLOWFISHENCRYPTECB + (blockCipherModcrypt) blowfishDecryptECB, + #else + (blockCipherModcrypt) 0 + #endif + }, + /* cbc */ + { + (blockCipherModcrypt) 0, + (blockCipherModcrypt) 0 + }, + (blockCipherFeedback) blowfishFeedback +}; + +int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation op) +{ + if ((op != ENCRYPT) && (op != DECRYPT)) + return -1; + + if (((keybits & 7) == 0) && (keybits >= 32) && (keybits <= 448)) + { + register uint32_t* p = bp->p; + register uint32_t* s = bp->s; + register unsigned int i, j, k; + + uint32_t tmp, work[2]; + + memcpy(s, _bf_s, 1024 * sizeof(uint32_t)); + + for (i = 0, k = 0; i < BLOWFISHPSIZE; i++) + { + tmp = 0; + for (j = 0; j < 4; j++) + { + tmp <<= 8; + tmp |= key[k++]; + if (k >= (keybits >> 3)) + k = 0; + } + p[i] = _bf_p[i] ^ tmp; + } + + work[0] = work[1] = 0; + + for (i = 0; i < BLOWFISHPSIZE; i += 2, p += 2) + { + blowfishEncrypt(bp, work, work); + #if WORDS_BIGENDIAN + p[0] = work[0]; + p[1] = work[1]; + #else + p[0] = swapu32(work[0]); + p[1] = swapu32(work[1]); + #endif + } + + for (i = 0; i < 1024; i += 2, s += 2) + { + blowfishEncrypt(bp, work, work); + #if WORDS_BIGENDIAN + s[0] = work[0]; + s[1] = work[1]; + #else + s[0] = swapu32(work[0]); + s[1] = swapu32(work[1]); + #endif + } + + /* clear fdback/iv */ + bp->fdback[0] = 0; + bp->fdback[1] = 0; + + return 0; + } + return -1; +} + +#ifndef ASM_BLOWFISHSETIV +int blowfishSetIV(blowfishParam* bp, const byte* iv) +{ + if (iv) + memcpy(bp->fdback, iv, 8); + else + memset(bp->fdback, 0, 8); + + return 0; +} +#endif + +int blowfishBlowit(blowfishParam* bp, uint32_t* dst, const uint32_t* src) +{ + register uint32_t xl = src[0], xr = src[1]; + register uint32_t* p = bp->p; + register uint32_t* s = bp->s; + + EROUND(xl, xr); EROUND(xr, xl); + + dst[1] = xr; + dst[0] = xl; + + return 0; +} + +#ifndef ASM_BLOWFISHENCRYPT +int blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src) +{ + #if WORDS_BIGENDIAN + register uint32_t xl = src[0], xr = src[1]; + #else + register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]); + #endif + register uint32_t* p = bp->p; + register uint32_t* s = bp->s; + + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + EROUND(xl, xr); EROUND(xr, xl); + + #if WORDS_BIGENDIAN + dst[1] = xl ^ *(p++); + dst[0] = xr ^ *(p++); + #else + dst[1] = swapu32(xl ^ *(p++)); + dst[0] = swapu32(xr ^ *(p++)); + #endif + + return 0; +} +#endif + +#ifndef ASM_BLOWFISHDECRYPT +int blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src) +{ + #if WORDS_BIGENDIAN + register uint32_t xl = src[0], xr = src[1]; + #else + register uint32_t xl = swapu32(src[0]), xr = swapu32(src[1]); + #endif + register uint32_t* p = bp->p+BLOWFISHPSIZE-1; + register uint32_t* s = bp->s; + + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + DROUND(xl, xr); DROUND(xr, xl); + + #if WORDS_BIGENDIAN + dst[1] = xl ^ *(p--); + dst[0] = xr ^ *(p--); + #else + dst[1] = swapu32(xl ^ *(p--)); + dst[0] = swapu32(xr ^ *(p--)); + #endif + + return 0; +} +#endif + +uint32_t* blowfishFeedback(blowfishParam* bp) +{ + return bp->fdback; +} diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h new file mode 100755 index 0000000000..1d95ddb4f2 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfish.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file blowfish.h + * \brief Blowfish block cipher. + * + * For more information on this blockcipher, see: + * "Applied Cryptography", second edition + * Bruce Schneier + * Wiley & Sons + * + * Also see http://www.counterpane.com/blowfish.html + * + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup BC_m BC_blowfish_m + */ + +#ifndef _BLOWFISH_H +#define _BLOWFISH_H + +#include "beecrypt/beecrypt.h" +#include "beecrypt/blowfishopt.h" + +#define BLOWFISHROUNDS 16 +#define BLOWFISHPSIZE (BLOWFISHROUNDS+2) + +/*!\brief Holds all the parameters necessary for the Blowfish cipher. + * \ingroup BC_blowfish_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI blowfishParam +#else +struct _blowfishParam +#endif +{ + /*!\var p + * \brief Holds the key expansion. + */ + uint32_t p[BLOWFISHPSIZE]; + /*!\var s + * \brief Holds the s-boxes. + */ + uint32_t s[1024]; + /*!\var fdback + * \brief Buffer to be used by block chaining or feedback modes. + */ + uint32_t fdback[2]; +}; + +#ifndef __cplusplus +typedef struct _blowfishParam blowfishParam; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\var blowfish + * \brief Holds the full API description of the Blowfish algorithm. + */ +extern const BEECRYPTAPI blockCipher blowfish; + +/*!\fn int blowfishSetup(blowfishParam* bp, const byte* key, size_t keybits, cipherOperation + op) + * \brief The function performs the cipher's key expansion. + * \param bp The cipher's parameter block. + * \param key The key value. + * \param keybits The number of bits in the key; legal values are: 32 to 448, + * in multiples of 8. + * \param op ENCRYPT or DECRYPT. + * \retval 0 on success. + * \retval -1 on failure. + */ +BEECRYPTAPI +int blowfishSetup (blowfishParam*, const byte*, size_t, cipherOperation); + +/*!\fn int blowfishSetIV(blowfishParam* bp, const byte* iv) + * \brief This function sets the Initialization Vector. + * \note This function is only useful in block chaining or feedback modes. + * \param bp The cipher's parameter block. + * \param iv The initialization vector; may be null. + * \retval 0 on success. + */ +BEECRYPTAPI +int blowfishSetIV (blowfishParam*, const byte*); + +/*!\fn blowfishEncrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src) + * \brief This function performs the Blowfish encryption; it encrypts one block + * of 64 bits. + * \param bp The cipher's parameter block. + * \param dst The ciphertext; should be aligned on 32-bit boundary. + * \param src The cleartext; should be aligned on 32-bit boundary. + * \retval 0 on success. + */ +BEECRYPTAPI +int blowfishEncrypt (blowfishParam*, uint32_t*, const uint32_t*); + +/*!\fn blowfishDecrypt(blowfishParam* bp, uint32_t* dst, const uint32_t* src) + * \brief This function performs the Blowfish decryption; it Rderypts one block + * of 64 bits. + * \param bp The cipher's parameter block. + * \param dst The cleartext; should be aligned on 32-bit boundary. + * \param src The ciphertext; should be aligned on 32-bit boundary. + * \retval 0 on success. + */ +BEECRYPTAPI +int blowfishDecrypt (blowfishParam*, uint32_t*, const uint32_t*); + +BEECRYPTAPI +uint32_t* blowfishFeedback(blowfishParam*); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h new file mode 100755 index 0000000000..f38db94b52 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/blowfishopt.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2000, 2002, 2003 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file blowfishopt.h + * \brief Blowfish block cipher, assembler-optimized routines, headers. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup BC_blowfish_m + */ + +#ifndef _BLOWFISHOPT_H +#define _BLOWFISHOPT_H + +#include "beecrypt/beecrypt.h" +#include "beecrypt/blowfish.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if WIN32 +# if defined(_MSC_VER) && defined(_M_IX86) +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# elif __INTEL__ && __MWERKS__ +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# endif +#endif + +#if defined(__GNUC__) +# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# endif +# if defined(OPTIMIZE_POWERPC) +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# endif +#endif + +#if defined(__IBMC__) +# if defined(OPTIMIZE_POWERPC) +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# endif +#endif + +#if defined(__INTEL_COMPILER) +# if defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_BLOWFISHENCRYPT +# define ASM_BLOWFISHDECRYPT +# endif +#endif + +#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) +/* nothing here yet */ +#endif + +#undef ASM_BLOWFISHENCRYPT +#undef ASM_BLOWFISHDECRYPT + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c new file mode 100755 index 0000000000..8a0999b63e --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1998, 1999, 2000, 2001 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file endianness.c + * \brief Endian-dependant encoding/decoding. + * \author Bob Deblier <bob.deblier@pandora.be> + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H +# include <endian.h> +#endif + +#include "beecrypt/endianness.h" + +#undef swap16 +#undef swapu16 +#undef swap32 +#undef swapu32 +#undef swap64 +#undef swapu64 + +int16_t swap16(int16_t n) +{ + return ( ((n & 0xff) << 8) | + ((n & 0xff00) >> 8) ); +} + +uint16_t swapu16(uint16_t n) +{ + return ( ((n & 0xffU) << 8) | + ((n & 0xff00U) >> 8) ); +} + +int32_t swap32(int32_t n) +{ + return ( ((n & 0xff) << 24) | + ((n & 0xff00) << 8) | + ((n & 0xff0000) >> 8) | + ((n & 0xff000000) >> 24) ); +} + +uint32_t swapu32(uint32_t n) +{ + return ( ((n & 0xffU) << 24) | + ((n & 0xff00U) << 8) | + ((n & 0xff0000U) >> 8) | + ((n & 0xff000000U) >> 24) ); +} + +int64_t swap64(int64_t n) +{ + return ( ((n & (((int64_t) 0xff) )) << 56) | + ((n & (((int64_t) 0xff) << 8)) << 40) | + ((n & (((int64_t) 0xff) << 16)) << 24) | + ((n & (((int64_t) 0xff) << 24)) << 8) | + ((n & (((int64_t) 0xff) << 32)) >> 8) | + ((n & (((int64_t) 0xff) << 40)) >> 24) | + ((n & (((int64_t) 0xff) << 48)) >> 40) | + ((n & (((int64_t) 0xff) << 56)) >> 56) ); +} + +uint64_t swapu64(uint64_t n) +{ + return ( ((n & (((uint64_t) 0xff) )) << 56) | + ((n & (((uint64_t) 0xff) << 8)) << 40) | + ((n & (((uint64_t) 0xff) << 16)) << 24) | + ((n & (((uint64_t) 0xff) << 24)) << 8) | + ((n & (((uint64_t) 0xff) << 32)) >> 8) | + ((n & (((uint64_t) 0xff) << 40)) >> 24) | + ((n & (((uint64_t) 0xff) << 48)) >> 40) | + ((n & (((uint64_t) 0xff) << 56)) >> 56) ); +} diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h new file mode 100755 index 0000000000..e136aa59f9 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/endianness.h @@ -0,0 +1,128 @@ +/* + * endianness.h + * + * Endian-dependant encoding/decoding, header + * + * Copyright (c) 1998, 1999, 2000, 2001, 2004 Beeyond Software Holding + * + * Author: Bob Deblier <bob.deblier@telenet.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#ifndef _ENDIANNESS_H +#define _ENDIANNESS_H + +#include "beecrypt/beecrypt.h" + +#if defined(__cplusplus) || HAVE_INLINE + +static inline int16_t _swap16(int16_t n) +{ + return ( ((n & 0xff) << 8) | + ((n & 0xff00) >> 8) ); +} +# define swap16(n) _swap16(n) + +static inline uint16_t _swapu16(uint16_t n) +{ + return ( ((n & 0xffU) << 8) | + ((n & 0xff00U) >> 8) ); +} +# define swapu16(n) _swap16(n) + +# ifdef __arch__swab32 +# define swap32(n) __arch__swab32(n) +# define swapu32(n) __arch__swab32(n) +# else + +static inline int32_t _swap32(int32_t n) +{ + return ( ((n & 0xff) << 24) | + ((n & 0xff00) << 8) | + ((n & 0xff0000) >> 8) | + ((n & 0xff000000) >> 24) ); +} +# define swap32(n) _swap32(n) + +static inline uint32_t _swapu32(uint32_t n) +{ + return ( ((n & 0xffU) << 24) | + ((n & 0xff00U) << 8) | + ((n & 0xff0000U) >> 8) | + ((n & 0xff000000U) >> 24) ); +} +# define swapu32(n) _swapu32(n) + +# endif + +# ifdef __arch__swab64 +# define swap64(n) __arch__swab64(n) +# define swapu64(n) __arch__swab64(n) +# else + +static inline int64_t _swap64(int64_t n) +{ + return ( ((n & ((int64_t) 0xff) ) << 56) | + ((n & ((int64_t) 0xff) << 8) << 40) | + ((n & ((int64_t) 0xff) << 16) << 24) | + ((n & ((int64_t) 0xff) << 24) << 8) | + ((n & ((int64_t) 0xff) << 32) >> 8) | + ((n & ((int64_t) 0xff) << 40) >> 24) | + ((n & ((int64_t) 0xff) << 48) >> 40) | + ((n & ((int64_t) 0xff) << 56) >> 56) ); +} +# define swap64(n) _swap64(n) + +static inline uint64_t _swapu64(uint64_t n) +{ + return ( ((n & ((uint64_t) 0xff) ) << 56) | + ((n & ((uint64_t) 0xff) << 8) << 40) | + ((n & ((uint64_t) 0xff) << 16) << 24) | + ((n & ((uint64_t) 0xff) << 24) << 8) | + ((n & ((uint64_t) 0xff) << 32) >> 8) | + ((n & ((uint64_t) 0xff) << 40) >> 24) | + ((n & ((uint64_t) 0xff) << 48) >> 40) | + ((n & ((uint64_t) 0xff) << 56) >> 56) ); +} +# define swapu64(n) _swapu64(n) + +# endif + +#else +BEECRYPTAPI + int16_t swap16 (int16_t); +BEECRYPTAPI +uint16_t swapu16(uint16_t); +BEECRYPTAPI + int32_t swap32 (int32_t); +BEECRYPTAPI +uint32_t swapu32(uint32_t); +BEECRYPTAPI + int64_t swap64 (int64_t); +BEECRYPTAPI +uint64_t swapu64(uint64_t); +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h new file mode 100755 index 0000000000..18386ef997 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/gnu.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2003 Bob Deblier + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#ifndef _BEECRYPT_GNU_H +#define _BEECRYPT_GNU_H + +#include <inttypes.h> +#include <stdint.h> + + +#include <pthread.h> +#include <stdio.h> +#include <stdlib.h> + +#include <string.h> +#include <unistd.h> +#include <dlfcn.h> + +typedef pthread_cond_t bc_cond_t; +typedef pthread_mutex_t bc_mutex_t; +typedef pthread_t bc_thread_t; + + + + + + + + + + + + + +#if defined(__GNUC__) +# if !defined(__GNUC_PREREQ__) +# define __GNUC_PREREQ__(maj, min) (__GNUC__ > (maj) || __GNUC__ == (maj) && __GNUC_MINOR__ >= (min)) +# endif +#else +# define __GNUC__ 0 +# define __GNUC_PREREQ__(maj, min) 0 +#endif + +/* WARNING: overriding this value is dangerous; some assembler routines + * make assumptions about the size set by the configure script + */ +#if !defined(MP_WBITS) +# define MP_WBITS 64U +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c new file mode 100755 index 0000000000..c28770a05b --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file hmac.c + * \brief HMAC algorithm. + * + * \see RFC2104 HMAC: Keyed-Hashing for Message Authentication. + * H. Krawczyk, M. Bellare, R. Canetti. + * + * \author Bob Deblier <bob.deblier@pandore.be> + * \ingroup HMAC_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/hmac.h" +#include "beecrypt/endianness.h" + +/*!\addtogroup HMAC_m + * \{ + */ + +#define HMAC_IPAD 0x36 +#define HMAC_OPAD 0x5c + +int hmacSetup(byte* kxi, byte* kxo, const hashFunction* hash, hashFunctionParam* param, const byte* key, size_t keybits) +{ + register unsigned int i; + + size_t keybytes = keybits >> 3; + + /* if the key is too large, hash it first */ + if (keybytes > hash->blocksize) + { + /* if the hash digest is too large, this doesn't help; this is really a sanity check */ + if (hash->digestsize > hash->blocksize) + return -1; + + if (hash->reset(param)) + return -1; + + if (hash->update(param, key, keybytes)) + return -1; + + if (hash->digest(param, kxi)) + return -1; + + memcpy(kxo, kxi, keybytes = hash->digestsize); + } + else if (keybytes > 0) + { + memcpy(kxi, key, keybytes); + memcpy(kxo, key, keybytes); + } + else + return -1; + + for (i = 0; i < keybytes; i++) + { + kxi[i] ^= HMAC_IPAD; + kxo[i] ^= HMAC_OPAD; + } + + for (i = keybytes; i < hash->blocksize; i++) + { + kxi[i] = HMAC_IPAD; + kxo[i] = HMAC_OPAD; + } + + return hmacReset(kxi, hash, param); +} + +int hmacReset(const byte* kxi, const hashFunction* hash, hashFunctionParam* param) +{ + if (hash->reset(param)) + return -1; + if (hash->update(param, kxi, hash->blocksize)) + return -1; + + return 0; +} + +int hmacUpdate(const hashFunction* hash, hashFunctionParam* param, const byte* data, size_t size) +{ + return hash->update(param, data, size); +} + +int hmacDigest(const byte* kxo, const hashFunction* hash, hashFunctionParam* param, byte* data) +{ + if (hash->digest(param, data)) + return -1; + if (hash->update(param, kxo, hash->blocksize)) + return -1; + if (hash->update(param, data, hash->digestsize)) + return -1; + if (hash->digest(param, data)) + return -1; + + return 0; +} + +/*!\} + */ diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h new file mode 100755 index 0000000000..709bb079f0 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmac.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1999, 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file hmac.h + * \brief HMAC algorithm, headers. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup HMAC_m + */ + +#ifndef _HMAC_H +#define _HMAC_H + +#include "beecrypt/beecrypt.h" + +/*!\ingroup HMAC_m + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* not used directly as keyed hash function, but instead used as generic methods */ + +BEECRYPTAPI +int hmacSetup ( byte*, byte*, const hashFunction*, hashFunctionParam*, const byte*, size_t); +BEECRYPTAPI +int hmacReset (const byte*, const hashFunction*, hashFunctionParam*); +BEECRYPTAPI +int hmacUpdate( const hashFunction*, hashFunctionParam*, const byte*, size_t); +BEECRYPTAPI +int hmacDigest( const byte*, const hashFunction*, hashFunctionParam*, byte*); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c new file mode 100755 index 0000000000..f201a45f0f --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file hmacsha1.c + * \brief HMAC-SHA-1 message authentication code. + * + * \see RFC2202 - Test Cases for HMAC-MD5 and HMAC-SHA-1. + * P. Cheng, R. Glenn. + * + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup HMAC_m HMAC_sha1_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/hmacsha1.h" + +/*!\addtogroup HMAC_sha1_m + * \{ + */ + +const keyedHashFunction hmacsha1 = { + "HMAC-SHA-1", + sizeof(hmacsha1Param), + 64, + 20, + 64, + 512, + 32, + (keyedHashFunctionSetup) hmacsha1Setup, + (keyedHashFunctionReset) hmacsha1Reset, + (keyedHashFunctionUpdate) hmacsha1Update, + (keyedHashFunctionDigest) hmacsha1Digest +}; + +int hmacsha1Setup (hmacsha1Param* sp, const byte* key, size_t keybits) +{ + return hmacSetup(sp->kxi, sp->kxo, &sha1, &sp->sparam, key, keybits); +} + +int hmacsha1Reset (hmacsha1Param* sp) +{ + return hmacReset(sp->kxi, &sha1, &sp->sparam); +} + +int hmacsha1Update(hmacsha1Param* sp, const byte* data, size_t size) +{ + return hmacUpdate(&sha1, &sp->sparam, data, size); +} + +int hmacsha1Digest(hmacsha1Param* sp, byte* data) +{ + return hmacDigest(sp->kxo, &sha1, &sp->sparam, data); +} + +/*!\} + */ diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h new file mode 100755 index 0000000000..207f5df37f --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/hmacsha1.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file hmacsha1.h + * \brief HMAC-SHA-1 message authentication code, headers. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup HMAC_m HMAC_sha1_m + */ + +#ifndef _HMACSHA1_H +#define _HMACSHA1_H + +#include "beecrypt/hmac.h" +#include "beecrypt/sha1.h" + +/*!\ingroup HMAC_sha1_m + */ +typedef struct +{ + sha1Param sparam; + byte kxi[64]; + byte kxo[64]; +} hmacsha1Param; + +#ifdef __cplusplus +extern "C" { +#endif + +extern BEECRYPTAPI const keyedHashFunction hmacsha1; + +BEECRYPTAPI +int hmacsha1Setup (hmacsha1Param*, const byte*, size_t); +BEECRYPTAPI +int hmacsha1Reset (hmacsha1Param*); +BEECRYPTAPI +int hmacsha1Update(hmacsha1Param*, const byte*, size_t); +BEECRYPTAPI +int hmacsha1Digest(hmacsha1Param*, byte*); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h new file mode 100755 index 0000000000..4778b7ca89 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/memchunk.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2001 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/*!\file memchunk.h + * \author Bob Deblier <bob.deblier@pandora.be> + */ + +#ifndef _MEMCHUNK_H +#define _MEMCHUNK_H + +#include "beecrypt/api.h" + +typedef struct +{ + size_t size; + byte* data; +} memchunk; + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +memchunk* memchunkAlloc(size_t); +BEECRYPTAPI +void memchunkWipe(memchunk*); +BEECRYPTAPI +void memchunkFree(memchunk*); +BEECRYPTAPI +memchunk* memchunkResize(memchunk*, size_t); +BEECRYPTAPI +memchunk* memchunkClone(const memchunk*); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c new file mode 100755 index 0000000000..82d272c17a --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.c @@ -0,0 +1,1537 @@ +/* + * Copyright (c) 2002, 2003 Bob Deblier + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file mp.c + * \brief Multi-precision integer routines. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup MP_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/mp.h" +#include "beecrypt/mpopt.h" + +#ifndef ASM_MPZERO +void mpzero(size_t size, mpw* data) +{ + while (size--) + *(data++) = 0; +} +#endif + +#ifndef ASM_MPFILL +void mpfill(size_t size, mpw* data, mpw fill) +{ + while (size--) + *(data++) = fill; +} +#endif + +#ifndef ASM_MPODD +int mpodd(size_t size, const mpw* data) +{ + return (int)(data[size-1] & 0x1); +} +#endif + +#ifndef ASM_MPEVEN +int mpeven(size_t size, const mpw* data) +{ + return !(int)(data[size-1] & 0x1); +} +#endif + +#ifndef ASM_MPZ +int mpz(size_t size, const mpw* data) +{ + while (size--) + if (*(data++)) + return 0; + return 1; +} +#endif + +#ifndef ASM_MPNZ +int mpnz(size_t size, const mpw* data) +{ + while (size--) + if (*(data++)) + return 1; + return 0; +} +#endif + +#ifndef ASM_MPEQ +int mpeq(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata == *ydata) + { + xdata++; + ydata++; + } + else + return 0; + } + return 1; +} +#endif + +#ifndef ASM_MPEQX +int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpeq(ysize, xdata+diff, ydata) && mpz(diff, xdata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpeq(xsize, ydata+diff, xdata) && mpz(diff, ydata); + } + else + return mpeq(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPNE +int mpne(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata == *ydata) + { + xdata++; + ydata++; + } + else + return 1; + } + return 0; +} +#endif + +#ifndef ASM_MPNEX +int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpnz(diff, xdata) || mpne(ysize, xdata+diff, ydata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpnz(diff, ydata) || mpne(xsize, ydata+diff, xdata); + } + else + return mpne(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPGT +int mpgt(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata < *ydata) + return 0; + if (*xdata > *ydata) + return 1; + xdata++; ydata++; + } + return 0; +} +#endif + +#ifndef ASM_MPGTX +int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpnz(diff, xdata) || mpgt(ysize, xdata + diff, ydata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpz(diff, ydata) && mpgt(xsize, xdata, ydata + diff); + } + else + return mpgt(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPLT +int mplt(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata > *ydata) + return 0; + if (*xdata < *ydata) + return 1; + xdata++; ydata++; + } + return 0; +} +#endif + +#ifndef ASM_MPLTX +int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpz(diff, xdata) && mplt(ysize, xdata+diff, ydata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpnz(diff, ydata) || mplt(xsize, xdata, ydata+diff); + } + else + return mplt(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPGE +int mpge(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata < *ydata) + return 0; + if (*xdata > *ydata) + return 1; + xdata++; ydata++; + } + return 1; +} +#endif + +#ifndef ASM_MPGEX +int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpnz(diff, xdata) || mpge(ysize, xdata+diff, ydata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpz(diff, ydata) && mpge(xsize, xdata, ydata+diff); + } + else + return mpge(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPLE +int mple(size_t size, const mpw* xdata, const mpw* ydata) +{ + while (size--) + { + if (*xdata < *ydata) + return 1; + if (*xdata > *ydata) + return 0; + xdata++; ydata++; + } + return 1; +} +#endif + +#ifndef ASM_MPLEX +int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpz(diff, xdata) && mple(ysize, xdata+ diff, ydata); + } + else if (xsize < ysize) + { + register size_t diff = ysize - xsize; + return mpnz(diff, ydata) || mple(xsize, xdata, ydata+diff); + } + else + return mple(xsize, xdata, ydata); +} +#endif + +#ifndef ASM_MPISONE +int mpisone(size_t size, const mpw* data) +{ + data += size; + if (*(--data) == 1) + { + while (--size) + if (*(--data)) + return 0; + return 1; + } + return 0; +} +#endif + +#ifndef ASM_MPISTWO +int mpistwo(size_t size, const mpw* data) +{ + data += size; + if (*(--data) == 2) + { + while (--size) + if (*(--data)) + return 0; + return 1; + } + return 0; +} +#endif + +#ifndef ASM_MPEQMONE +int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata) +{ + xdata += size; + ydata += size; + + if (*(--xdata)+1 == *(--ydata)) + { + while (--size) + if (*(--xdata) != *(--ydata)) + return 0; + return 1; + } + return 0; +} +#endif + +#ifndef ASM_MPLEONE +int mpleone(size_t size, const mpw* data) +{ + data += size; + if (*(--data) > 1) + return 0; + else + { + while (--size) + if (*(--data)) + return 0; + return 1; + } +} +#endif + +#ifndef ASM_MPMSBSET +int mpmsbset(size_t size, const mpw* data) +{ + return (int)((*data) >> (MP_WBITS-1)); +} +#endif + +#ifndef ASM_MPLSBSET +int mplsbset(size_t size, const mpw* data) +{ + return (int)(data[size-1] & 0x1); +} +#endif + +#ifndef ASM_MPSETMSB +void mpsetmsb(size_t size, mpw* data) +{ + *data |= MP_MSBMASK; +} +#endif + +#ifndef ASM_MPSETLSB +void mpsetlsb(size_t size, mpw* data) +{ + data[size-1] |= MP_LSBMASK; +} +#endif + +#ifndef ASM_MPCLRMSB +void mpclrmsb(size_t size, mpw* data) +{ + *data &= ~ MP_MSBMASK; +} +#endif + +#ifndef ASM_MPCLRLSB +void mpclrlsb(size_t size, mpw* data) +{ + data[size-1] &= ~ MP_LSBMASK; +} +#endif + +#ifndef ASM_MPAND +void mpand(size_t size, mpw* xdata, const mpw* ydata) +{ + while (size--) + xdata[size] &= ydata[size]; +} +#endif + +#ifndef ASM_MPOR +void mpor(size_t size, mpw* xdata, const mpw* ydata) +{ + while (size--) + xdata[size] |= ydata[size]; +} +#endif + +#ifndef ASM_MPXOR +void mpxor(size_t size, mpw* xdata, const mpw* ydata) +{ + while (size--) + xdata[size] ^= ydata[size]; +} +#endif + +#ifndef ASM_MPNOT +void mpnot(size_t size, mpw* data) +{ + while (size--) + data[size] = ~data[size]; +} +#endif + +#ifndef ASM_MPSETW +void mpsetw(size_t size, mpw* xdata, mpw y) +{ + while (--size) + *(xdata++) = 0; + *(xdata++) = y; +} +#endif + +#ifndef ASM_MPSETX +void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) +{ + while (xsize > ysize) + { + xsize--; + *(xdata++) = 0; + } + while (ysize > xsize) + { + ysize--; + ydata++; + } + while (xsize--) + *(xdata++) = *(ydata++); +} +#endif + +#ifndef ASM_MPADDW +int mpaddw(size_t size, mpw* xdata, mpw y) +{ + register mpw load, temp; + register int carry = 0; + + xdata += size-1; + + load = *xdata; + temp = load + y; + *(xdata--) = temp; + carry = (load > temp); + + while (--size && carry) + { + load = *xdata; + temp = load + 1; + *(xdata--) = temp; + carry = (load > temp); + } + return carry; +} +#endif + +#ifndef ASM_MPADD +int mpadd(size_t size, mpw* xdata, const mpw* ydata) +{ + register mpw load, temp; + register int carry = 0; + + xdata += size-1; + ydata += size-1; + + while (size--) + { + temp = *(ydata--); + load = *xdata; + temp = carry ? (load + temp + 1) : (load + temp); + *(xdata--) = temp; + carry = carry ? (load >= temp) : (load > temp); + } + return carry; +} +#endif + +#ifndef ASM_MPADDX +int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpaddw(diff, xdata, (mpw) mpadd(ysize, xdata+diff, ydata)); + } + else + { + register size_t diff = ysize - xsize; + return mpadd(xsize, xdata, ydata+diff); + } +} +#endif + +#ifndef ASM_MPSUBW +int mpsubw(size_t size, mpw* xdata, mpw y) +{ + register mpw load, temp; + register int carry = 0; + + xdata += size-1; + + load = *xdata; + temp = load - y; + *(xdata--) = temp; + carry = (load < temp); + + while (--size && carry) + { + load = *xdata; + temp = load - 1; + *(xdata--) = temp; + carry = (load < temp); + } + return carry; +} +#endif + +#ifndef ASM_MPSUB +int mpsub(size_t size, mpw* xdata, const mpw* ydata) +{ + register mpw load, temp; + register int carry = 0; + + xdata += size-1; + ydata += size-1; + + while (size--) + { + temp = *(ydata--); + load = *xdata; + temp = carry ? (load - temp - 1) : (load - temp); + *(xdata--) = temp; + carry = carry ? (load <= temp) : (load < temp); + } + return carry; +} +#endif + +#ifndef ASM_MPSUBX +int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) +{ + if (xsize > ysize) + { + register size_t diff = xsize - ysize; + return mpsubw(diff, xdata, (mpw) mpsub(ysize, xdata+diff, ydata)); + } + else + { + register size_t diff = ysize - xsize; + return mpsub(xsize, xdata, ydata+diff); + } +} +#endif + +#ifndef ASM_MPNEG +void mpneg(size_t size, mpw* data) +{ + mpnot(size, data); + mpaddw(size, data, 1); +} +#endif + +#ifndef ASM_MPSETMUL +mpw mpsetmul(size_t size, mpw* result, const mpw* data, mpw y) +{ + #if HAVE_MPDW + register mpdw temp; + register mpw carry = 0; + + data += size; + result += size; + + while (size--) + { + temp = *(--data); + temp *= y; + temp += carry; + *(--result) = (mpw) temp; + carry = (mpw)(temp >> MP_WBITS); + } + #else + register mpw temp, load, carry = 0; + register mphw ylo, yhi; + + ylo = (mphw) y; + yhi = (mphw) (y >> MP_HWBITS); + + data += size; + result += size; + + while (size--) + { + register mphw xlo, xhi; + register mpw rlo, rhi; + + xlo = (mphw) (temp = *(--data)); + xhi = (mphw) (temp >> MP_HWBITS); + + rlo = (mpw) xlo * ylo; + rhi = (mpw) xhi * yhi; + load = rlo; + temp = (mpw) xhi * ylo; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + temp = (mpw) xlo * yhi; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + temp = rlo + carry; + carry = rhi + (load > temp); + *(--result) = temp; + } + #endif + return carry; +} +#endif + +#ifndef ASM_MPADDMUL +mpw mpaddmul(size_t size, mpw* result, const mpw* data, mpw y) +{ + #if HAVE_MPDW + register mpdw temp; + register mpw carry = 0; + + data += size; + result += size; + + while (size--) + { + temp = *(--data); + temp *= y; + temp += carry; + temp += *(--result); + *result = (mpw) temp; + carry = (mpw)(temp >> MP_WBITS); + } + #else + register mpw temp, load, carry = 0; + register mphw ylo, yhi; + + ylo = (mphw) y; + yhi = (mphw) (y >> MP_HWBITS); + + data += size; + result += size; + + while (size--) + { + register mphw xlo, xhi; + register mpw rlo, rhi; + + xlo = (mphw) (temp = *(--data)); + xhi = (mphw) (temp >> MP_HWBITS); + + rlo = (mpw) xlo * ylo; + rhi = (mpw) xhi * yhi; + load = rlo; + temp = (mpw) xhi * ylo; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + temp = (mpw) xlo * yhi; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + rlo += carry; + temp = (load > rlo); + load = rhi; + rhi += temp; + carry = (load > rhi); + load = rlo; + rlo += *(--result); + *result = rlo; + carry += rhi + (load > rlo); + } + #endif + return carry; +} +#endif + +#ifndef ASM_MPMUL +void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) +{ + /* preferred passing of parameters is x the larger of the two numbers */ + if (xsize >= ysize) + { + register mpw rc; + + result += ysize; + ydata += ysize; + + rc = mpsetmul(xsize, result, xdata, *(--ydata)); + *(--result) = rc; + + while (--ysize) + { + rc = mpaddmul(xsize, result, xdata, *(--ydata)); + *(--result) = rc; + } + } + else + { + register mpw rc; + + result += xsize; + xdata += xsize; + + rc = mpsetmul(ysize, result, ydata, *(--xdata)); + *(--result) = rc; + + while (--xsize) + { + rc = mpaddmul(ysize, result, ydata, *(--xdata)); + *(--result) = rc; + } + } +} +#endif + +#ifndef ASM_MPADDSQRTRC +void mpaddsqrtrc(size_t size, mpw* result, const mpw* data) +{ + #if HAVE_MPDW + register mpdw temp; + register mpw load, carry = 0; + + result += (size << 1); + + while (size--) + { + temp = load = data[size]; + temp *= load; + temp += carry; + temp += *(--result); + *result = (mpw) temp; + temp >>= MP_WBITS; + temp += *(--result); + *result = (mpw) temp; + carry = (mpw)(temp >> MP_WBITS); + } + #else + register mpw temp, load, carry = 0; + + result += (size << 1); + + while (size--) + { + register mphw xlo, xhi; + register mpw rlo, rhi; + + xlo = (mphw) (temp = data[size]); + xhi = (mphw) (temp >> MP_HWBITS); + + rlo = (mpw) xlo * xlo; + rhi = (mpw) xhi * xhi; + temp = (mpw) xhi * xlo; + load = rlo; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + rlo += (temp << MP_HWBITS); + rhi += (temp >> MP_HWBITS) + (load > rlo); + load = rlo; + rlo += carry; + rhi += (load > rlo); + load = rlo; + rlo += *(--result); + *result = rlo; + temp = (load > rlo); + load = rhi; + rhi += temp; + carry = (load > rhi); + load = rhi; + rhi += *(--result); + *result = rhi; + carry += (load > rhi); + } + #endif +} +#endif + +#ifndef ASM_MPSQR +void mpsqr(mpw* result, size_t size, const mpw* data) +{ + register mpw rc; + register size_t n = size-1; + + result += size; + result[n] = 0; + + if (n) + { + rc = mpsetmul(n, result, data, data[n]); + *(--result) = rc; + while (--n) + { + rc = mpaddmul(n, result, data, data[n]); + *(--result) = rc; + } + } + + *(--result) = 0; + + mpmultwo(size << 1, result); + + mpaddsqrtrc(size, result, data); +} +#endif + +#ifndef ASM_MPSIZE +size_t mpsize(size_t size, const mpw* data) +{ + while (size) + { + if (*data) + return size; + data++; + size--; + } + return 0; +} +#endif + +#ifndef ASM_MPBITS +size_t mpbits(size_t size, const mpw* data) +{ + return MP_WORDS_TO_BITS(size) - mpmszcnt(size, data); +} +#endif + +#ifndef ASM_MPNORM +size_t mpnorm(size_t size, mpw* data) +{ + register size_t shift = mpmszcnt(size, data); + mplshift(size, data, shift); + return shift; +} +#endif + +#ifndef ASM_MPDIVTWO +void mpdivtwo(size_t size, mpw* data) +{ + register mpw temp, carry = 0; + + while (size--) + { + temp = *data; + *(data++) = (temp >> 1) | carry; + carry = (temp << (MP_WBITS-1)); + } +} +#endif + +#ifndef ASM_MPSDIVTWO +void mpsdivtwo(size_t size, mpw* data) +{ + int carry = mpmsbset(size, data); + mpdivtwo(size, data); + if (carry) + mpsetmsb(size, data); +} +#endif + +#ifndef ASM_MPMULTWO +int mpmultwo(size_t size, mpw* data) +{ + register mpw temp, carry = 0; + + data += size; + while (size--) + { + temp = *(--data); + *data = (temp << 1) | carry; + carry = (temp >> (MP_WBITS-1)); + } + return (int) carry; +} +#endif + +#ifndef ASM_MPMSZCNT +size_t mpmszcnt(size_t size, const mpw* data) +{ + register size_t zbits = 0; + register size_t i = 0; + + while (i < size) + { + register mpw temp = data[i++]; + if (temp) + { + while (!(temp & MP_MSBMASK)) + { + zbits++; + temp <<= 1; + } + break; + } + else + zbits += MP_WBITS; + } + return zbits; +} +#endif + +#ifndef ASM_MPLSZCNT +size_t mplszcnt(size_t size, const mpw* data) +{ + register size_t zbits = 0; + + while (size--) + { + register mpw temp = data[size]; + if (temp) + { + while (!(temp & MP_LSBMASK)) + { + zbits++; + temp >>= 1; + } + break; + } + else + zbits += MP_WBITS; + } + return zbits; +} +#endif + +#ifndef ASM_MPLSHIFT +void mplshift(size_t size, mpw* data, size_t count) +{ + register size_t words = MP_BITS_TO_WORDS(count); + + if (words < size) + { + register short lbits = (short) (count & (MP_WBITS-1)); + + /* first do the shifting, then do the moving */ + if (lbits) + { + register mpw temp, carry = 0; + register short rbits = MP_WBITS - lbits; + register size_t i = size; + + while (i > words) + { + temp = data[--i]; + data[i] = (temp << lbits) | carry; + carry = (temp >> rbits); + } + } + if (words) + { + mpmove(size-words, data, data+words); + mpzero(words, data+size-words); + } + } + else + mpzero(size, data); +} +#endif + +#ifndef ASM_MPRSHIFT +void mprshift(size_t size, mpw* data, size_t count) +{ + register size_t words = MP_BITS_TO_WORDS(count); + + if (words < size) + { + register short rbits = (short) (count & (MP_WBITS-1)); + + /* first do the shifting, then do the moving */ + if (rbits) + { + register mpw temp, carry = 0; + register short lbits = MP_WBITS - rbits; + register size_t i = 0; + + while (i < size-words) + { + temp = data[i]; + data[i++] = (temp >> rbits) | carry; + carry = (temp << lbits); + } + } + if (words) + { + mpmove(size-words, data+words, data); + mpzero(words, data); + } + } + else + mpzero(size, data); +} +#endif + +#ifndef ASM_MPRSHIFTLSZ +size_t mprshiftlsz(size_t size, mpw* data) +{ + register mpw* slide = data+size-1; + register size_t zwords = 0; /* counter for 'all zero bit' words */ + register short lbits, rbits = 0; /* counter for 'least significant zero' bits */ + register mpw temp, carry = 0; + + data = slide; + + /* count 'all zero' words and move src pointer */ + while (size--) + { + /* test if we have a non-zero word */ + if ((carry = *(slide--))) + { + /* count 'least signification zero bits and set zbits counter */ + while (!(carry & MP_LSBMASK)) + { + carry >>= 1; + rbits++; + } + break; + } + zwords++; + } + + if ((rbits == 0) && (zwords == 0)) + return 0; + + /* prepare right-shifting of data */ + lbits = MP_WBITS - rbits; + + /* shift data */ + while (size--) + { + temp = *(slide--); + *(data--) = (temp << lbits) | carry; + carry = (temp >> rbits); + } + + /* store the final carry */ + *(data--) = carry; + + /* store the return value in size */ + size = MP_WORDS_TO_BITS(zwords) + rbits; + + /* zero the (zwords) most significant words */ + while (zwords--) + *(data--) = 0; + + return size; +} +#endif + +/* try an alternate version here, with descending sizes */ +/* also integrate lszcnt and rshift properly into one function */ +#ifndef ASM_MPGCD_W +/* + * mpgcd_w + * need workspace of (size) words + */ +void mpgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp) +{ + register size_t shift, temp; + + if (mpge(size, xdata, ydata)) + { + mpcopy(size, wksp, xdata); + mpcopy(size, result, ydata); + } + else + { + mpcopy(size, wksp, ydata); + mpcopy(size, result, xdata); + } + + /* get the smallest returned values, and set shift to that */ + + shift = mprshiftlsz(size, wksp); + temp = mprshiftlsz(size, result); + + if (shift > temp) + shift = temp; + + while (mpnz(size, wksp)) + { + mprshiftlsz(size, wksp); + mprshiftlsz(size, result); + + if (mpge(size, wksp, result)) + mpsub(size, wksp, result); + else + mpsub(size, result, wksp); + + /* slide past zero words in both operands by increasing pointers and decreasing size */ + if ((*wksp == 0) && (*result == 0)) + { + size--; + wksp++; + result++; + } + } + + /* figure out if we need to slide the result pointer back */ + if ((temp = MP_BITS_TO_WORDS(shift))) + { + size += temp; + result -= temp; + } + + mplshift(size, result, shift); +} +#endif + +#ifndef ASM_MPEXTGCD_W +/* needs workspace of (6*size+6) words */ +/* used to compute the modular inverse */ +int mpextgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp) +{ + /* + * For computing a modular inverse, pass the modulus as xdata and the number + * to be inverted as ydata. + * + * Fact: if a element of Zn, then a is invertible if and only if gcd(a,n) = 1 + * Hence: if n is even, then a must be odd, otherwise the gcd(a,n) >= 2 + * + * The calling routine must guarantee this condition. + */ + + register size_t sizep = size+1; + register int full; + + mpw* udata = wksp; + mpw* vdata = udata+sizep; + mpw* adata = vdata+sizep; + mpw* bdata = adata+sizep; + mpw* cdata = bdata+sizep; + mpw* ddata = cdata+sizep; + + mpsetx(sizep, udata, size, xdata); + mpsetx(sizep, vdata, size, ydata); + mpzero(sizep, bdata); + mpsetw(sizep, ddata, 1); + + if ((full = mpeven(sizep, udata))) + { + mpsetw(sizep, adata, 1); + mpzero(sizep, cdata); + } + + while (1) + { + while (mpeven(sizep, udata)) + { + mpdivtwo(sizep, udata); + + if (mpodd(sizep, bdata) || (full && mpodd(sizep, adata))) + { + if (full) mpaddx(sizep, adata, size, ydata); + mpsubx(sizep, bdata, size, xdata); + } + + if (full) mpsdivtwo(sizep, adata); + mpsdivtwo(sizep, bdata); + } + while (mpeven(sizep, vdata)) + { + mpdivtwo(sizep, vdata); + + if (mpodd(sizep, ddata) || (full && mpodd(sizep, cdata))) + { + if (full) mpaddx(sizep, cdata, size, ydata); + mpsubx(sizep, ddata, size, xdata); + } + + if (full) mpsdivtwo(sizep, cdata); + mpsdivtwo(sizep, ddata); + } + if (mpge(sizep, udata, vdata)) + { + mpsub(sizep, udata, vdata); + if (full) mpsub(sizep, adata, cdata); + mpsub(sizep, bdata, ddata); + } + else + { + mpsub(sizep, vdata, udata); + if (full) mpsub(sizep, cdata, adata); + mpsub(sizep, ddata, bdata); + } + if (mpz(sizep, udata)) + { + if (mpisone(sizep, vdata)) + { + if (result) + { + if (*ddata & MP_MSBMASK) + { + /* keep adding the modulus until we get a carry */ + while (!mpaddx(sizep, ddata, size, xdata)); + } + else + { + /* in some computations, d ends up > x, hence: + * keep subtracting n from d until d < x + */ + while (mpgtx(sizep, ddata, size, xdata)) + mpsubx(sizep, ddata, size, xdata); + } + mpsetx(size, result, sizep, ddata); + } + return 1; + } + return 0; + } + } +} +#endif + +#ifndef ASM_MPPNDIV +mpw mppndiv(mpw xhi, mpw xlo, mpw y) +{ + register mpw result = 0; + register short count = MP_WBITS; + register int carry = 0; + + while (count--) + { + if (carry | (xhi >= y)) + { + xhi -= y; + result++; + } + carry = (xhi >> (MP_WBITS-1)); + xhi <<= 1; + xhi |= (xlo >> (MP_WBITS-1)); + xlo <<= 1; + result <<= 1; + } + if (carry | (xhi >= y)) + { + xhi -= y; + result++; + } + return result; +} +#endif + +#ifndef ASM_MPMOD +void mpmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, mpw* workspace) +{ + /* result size xsize, workspace size 2*ysize+1 */ + mpw q, msw; + mpw* rdata = result; + mpw* ynorm = workspace+ysize+1; + size_t shift, qsize = xsize-ysize; + + mpcopy(ysize, ynorm, ydata); + shift = mpnorm(ysize, ynorm); + msw = *ynorm; + mpcopy(xsize, rdata, xdata); + if (mpge(ysize, rdata, ynorm)) + mpsub(ysize, rdata, ynorm); + + while (qsize--) + { + q = mppndiv(rdata[0], rdata[1], msw); + + *workspace = mpsetmul(ysize, workspace+1, ynorm, q); + + while (mplt(ysize+1, rdata, workspace)) + { + mpsubx(ysize+1, workspace, ysize, ynorm); + q--; + } + mpsub(ysize+1, rdata, workspace); + rdata++; + } + /* de-normalization steps */ + while (shift--) + { + mpdivtwo(ysize, ynorm); + if (mpge(ysize, rdata, ynorm)) + mpsub(ysize, rdata, ynorm); + } +} +#endif + +#ifndef ASM_MPNDIVMOD +void mpndivmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, register mpw* workspace) +{ + /* result must be xsize+1 in length */ + /* workspace must be ysize+1 in length */ + /* expect ydata to be normalized */ + mpw q; + mpw msw = *ydata; + size_t qsize = xsize-ysize; + + *result = (mpge(ysize, xdata, ydata) ? 1 : 0); + mpcopy(xsize, result+1, xdata); + + if (*result) + (void) mpsub(ysize, result+1, ydata); + + result++; + + while (qsize--) + { + q = mppndiv(result[0], result[1], msw); + + *workspace = mpsetmul(ysize, workspace+1, ydata, q); + + while (mplt(ysize+1, result, workspace)) + { + mpsubx(ysize+1, workspace, ysize, ydata); + q--; + } + mpsub(ysize+1, result, workspace); + *(result++) = q; + } +} +#endif + +void mpprint(size_t size, const mpw* data) +{ + mpfprint(stdout, size, data); +} + +void mpprintln(size_t size, const mpw* data) +{ + mpfprintln(stdout, size, data); +} + +void mpfprint(FILE* f, size_t size, const mpw* data) +{ + if (data == (mpw*) 0) + return; + + if (f == (FILE*) 0) + return; + + while (size--) + { + #if (MP_WBITS == 32) + fprintf(f, "%08x", (unsigned) *(data++)); + #elif (MP_WBITS == 64) + # if WIN32 + fprintf(f, "%016I64x", *(data++)); + # elif SIZEOF_UNSIGNED_LONG == 8 + fprintf(f, "%016lx", *(data++)); + # else + fprintf(f, "%016llx", *(data++)); + # endif + #else + # error + #endif + } + fflush(f); +} + +void mpfprintln(FILE* f, size_t size, const mpw* data) +{ + if (data == (mpw*) 0) + return; + + if (f == (FILE*) 0) + return; + + while (size--) + { + #if (MP_WBITS == 32) + fprintf(f, "%08x", *(data++)); + #elif (MP_WBITS == 64) + # if WIN32 + fprintf(f, "%016I64x", *(data++)); + # elif SIZEOF_UNSIGNED_LONG == 8 + fprintf(f, "%016lx", *(data++)); + # else + fprintf(f, "%016llx", *(data++)); + # endif + #else + # error + #endif + } + fprintf(f, "\n"); + fflush(f); +} + +int i2osp(byte *osdata, size_t ossize, const mpw* idata, size_t isize) +{ + #if WORDS_BIGENDIAN + size_t max_bytes = MP_WORDS_TO_BYTES(isize); + #endif + size_t significant_bytes = (mpbits(isize, idata) + 7) >> 3; + + /* verify that ossize is large enough to contain the significant bytes */ + if (ossize >= significant_bytes) + { + /* looking good; check if we have more space than significant bytes */ + if (ossize > significant_bytes) + { /* fill most significant bytes with zero */ + memset(osdata, 0, ossize - significant_bytes); + osdata += ossize - significant_bytes; + } + if (significant_bytes) + { /* fill remaining bytes with endian-adjusted data */ + #if !WORDS_BIGENDIAN + mpw w = idata[--isize]; + byte shift = 0; + + /* fill right-to-left; much easier than left-to-right */ + do + { + osdata[--significant_bytes] = (byte)(w >> shift); + shift += 8; + if (shift == MP_WBITS) + { + shift = 0; + w = idata[--isize]; + } + } while (significant_bytes); + #else + /* just copy data past zero bytes */ + memcpy(osdata, ((byte*) idata) + (max_bytes - significant_bytes), significant_bytes); + #endif + } + return 0; + } + return -1; +} + +int os2ip(mpw* idata, size_t isize, const byte* osdata, size_t ossize) +{ + size_t required; + + /* skip non-significant leading zero bytes */ + while (!(*osdata) && ossize) + { + osdata++; + ossize--; + } + + required = MP_BYTES_TO_WORDS(ossize + MP_WBYTES - 1); + + if (isize >= required) + { + /* yes, we have enough space and can proceed */ + mpw w = 0; + /* adjust counter so that the loop will start by skipping the proper + * amount of leading bytes in the first significant word + */ + byte b = (ossize % MP_WBYTES); + + if (isize > required) + { /* fill initials words with zero */ + mpzero(isize-required, idata); + idata += isize-required; + } + + if (b == 0) + b = MP_WBYTES; + + while (ossize--) + { + w <<= 8; + w |= *(osdata++); + b--; + + if (b == 0) + { + *(idata++) = w; + w = 0; + b = MP_WBYTES; + } + } + + return 0; + } + return -1; +} + +int hs2ip(mpw* idata, size_t isize, const char* hsdata, size_t hssize) +{ + size_t required = MP_NIBBLES_TO_WORDS(hssize + MP_WNIBBLES - 1); + + if (isize >= required) + { + register size_t i; + + + if (isize > required) + { /* fill initial words with zero */ + for (i = required; i < isize; i++) + *(idata++) = 0; + } + while (hssize) + { + register mpw w = 0; + register size_t chunk = hssize & (MP_WNIBBLES - 1); + register char ch; + + if (chunk == 0) chunk = MP_WNIBBLES; + + for (i = 0; i < chunk; i++) + { + ch = *(hsdata++); + w <<= 4; + if (ch >= '0' && ch <= '9') + w += (ch - '0'); + else if (ch >= 'A' && ch <= 'F') + w += (ch - 'A') + 10; + else if (ch >= 'a' && ch <= 'f') + w += (ch - 'a') + 10; + } + *(idata++) = w; + hssize -= chunk; + } + return 0; + } + return -1; +} diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h new file mode 100755 index 0000000000..57a3e6c502 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mp.h @@ -0,0 +1,691 @@ +/* + * Copyright (c) 2002, 2003 Bob Deblier + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file mp.h + * \brief Multi-precision integer routines. + * + * The routines declared here are all low-level operations, most of them + * suitable to be implemented in assembler. Prime candidates are in order + * of importance (according to gprof): + * <ul> + * <li>mpaddmul + * <li>mpsetmul + * <li>mpaddsqrtrc + * <li>mpsub + * <li>mpadd + * </ul> + * + * With some smart use of available assembler instructions, it's possible + * to speed these routines up by a factor of 2 to 4. + * + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup MP_m + */ + +#ifndef _MP_H +#define _MP_H + +#include "beecrypt/api.h" +#include "beecrypt/mpopt.h" + +#define MP_HWBITS (MP_WBITS >> 1) +#define MP_WBYTES (MP_WBITS >> 3) +#define MP_WNIBBLES (MP_WBITS >> 2) + +#if (MP_WBITS == 64) +# define MP_WORDS_TO_BITS(x) ((x) << 6) +# define MP_WORDS_TO_NIBBLES(x) ((x) << 4) +# define MP_WORDS_TO_BYTES(x) ((x) << 3) +# define MP_BITS_TO_WORDS(x) ((x) >> 6) +# define MP_NIBBLES_TO_WORDS(x) ((x) >> 4) +# define MP_BYTES_TO_WORDS(x) ((x) >> 3) +#elif (MP_WBITS == 32) +# define MP_WORDS_TO_BITS(x) ((x) << 5) +# define MP_WORDS_TO_NIBBLES(x) ((x) << 3) +# define MP_WORDS_TO_BYTES(x) ((x) << 2) +# define MP_BITS_TO_WORDS(x) ((x) >> 5) +# define MP_NIBBLES_TO_WORDS(x) ((x) >> 3) +# define MP_BYTES_TO_WORDS(x) ((x) >> 2) +#else +# error +#endif + +#define MP_MSBMASK (((mpw) 0x1) << (MP_WBITS-1)) +#define MP_LSBMASK ((mpw) 0x1) +#define MP_ALLMASK ~((mpw) 0x0) + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ASM_MPCOPY +# define mpcopy(size, dst, src) memcpy(dst, src, MP_WORDS_TO_BYTES(size)) +#else +BEECRYPTAPI +void mpcopy(size_t size, mpw* dest, const mpw* src); +#endif + +#ifndef ASM_MPMOVE +# define mpmove(size, dst, src) memmove(dst, src, MP_WORDS_TO_BYTES(size)) +#else +BEECRYPTAPI +void mpmove(size_t size, mpw* dest, const mpw* src); +#endif + +/*!\fn void mpzero(size_t size, mpw* data) + * \brief This function zeroes a multi-precision integer of a given size. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpzero(size_t size, mpw* data); + +/*!\fn void mpfill(size_t size, mpw* data, mpw fill) + * \brief This function fills each word of a multi-precision integer with a + * given value. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \param fill The value fill the data with. + */ +BEECRYPTAPI +void mpfill(size_t size, mpw* data, mpw fill); + +/*!\fn int mpodd(size_t size, const mpw* data) + * \brief This functions tests if a multi-precision integer is odd. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if odd + * \retval 0 if even + */ +BEECRYPTAPI +int mpodd (size_t size, const mpw* data); + +/*!\fn int mpeven(size_t size, const mpw* data) + * \brief This function tests if a multi-precision integer is even. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if even + * \retval 0 if odd + */ +BEECRYPTAPI +int mpeven(size_t size, const mpw* data); + +/*!\fn int mpz(size_t size, const mpw* data) + * \brief This function tests if a multi-precision integer is zero. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if zero + * \retval 0 if not zero + */ +BEECRYPTAPI +int mpz (size_t size, const mpw* data); + +/*!\fn int mpnz(size_t size, const mpw* data) + * \brief This function tests if a multi-precision integer is not zero. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if not zero + * \retval 0 if zero + */ +BEECRYPTAPI +int mpnz (size_t size, const mpw* data); + +/*!\fn int mpeq(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if two multi-precision integers of the same size + * are equal. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if equal + * \retval 0 if not equal + */ +BEECRYPTAPI +int mpeq (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mpne(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if two multi-precision integers of the same size + * differ. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if not equal + * \retval 0 if equal + */ +BEECRYPTAPI +int mpne (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mpgt(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of the same size is greater than the second. + * \note The comparison treats the arguments as unsigned. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if greater + * \retval 0 if less or equal + */ +BEECRYPTAPI +int mpgt (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mplt(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of the same size is less than the second. + * \note The comparison treats the arguments as unsigned. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if less + * \retval 0 if greater or equal + */ +BEECRYPTAPI +int mplt (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mpge(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of the same size is greater than or equal to the second. + * \note The comparison treats the arguments as unsigned. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if greater or equal + * \retval 0 if less + */ +BEECRYPTAPI +int mpge (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mple(size_t size, const mpw* xdata, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of the same size is less than or equal to the second. + * \note The comparison treats the arguments as unsigned. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if less or equal + * \retval 0 if greater + */ +BEECRYPTAPI +int mple (size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if two multi-precision integers of different + * size are equal. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if equal + * \retval 0 if not equal + */ +BEECRYPTAPI +int mpeqx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if two multi-precision integers of different + * size are equal. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if equal + * \retval 0 if not equal +*/ +BEECRYPTAPI +int mpnex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of different size is greater than the second. + * \note The comparison treats the arguments as unsigned. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if greater + * \retval 0 if less or equal + */ +BEECRYPTAPI +int mpgtx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of different size is less than the second. + * \note The comparison treats the arguments as unsigned. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if less + * \retval 0 if greater or equal + */ +BEECRYPTAPI +int mpltx(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of different size is greater than or equal to the second. + * \note The comparison treats the arguments as unsigned. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if greater or equal + * \retval 0 if less + */ +BEECRYPTAPI +int mpgex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function tests if the first of two multi-precision integers + * of different size is less than or equal to the second. + * \note The comparison treats the arguments as unsigned. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if less or equal + * \retval 0 if greater + */ +BEECRYPTAPI +int mplex(size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpisone(size_t size, const mpw* data) + * \brief This functions tests if the value of a multi-precision integer is + * equal to one. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if one + * \retval 0 if not one + */ +BEECRYPTAPI +int mpisone(size_t size, const mpw* data); + +/*!\fn int mpistwo(size_t size, const mpw* data) + * \brief This function tests if the value of a multi-precision integer is + * equal to two. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if two + * \retval 0 if not two + */ +BEECRYPTAPI +int mpistwo(size_t size, const mpw* data); + +/*!\fn int mpleone(size_t size, const mpw* data); + * \brief This function tests if the value of a multi-precision integer is + * less than or equal to one. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if less than or equal to one. + * \retval 0 if greater than one. + */ +BEECRYPTAPI +int mpleone(size_t size, const mpw* data); + +/*!\fn int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata); + * \brief This function tests if multi-precision integer x is equal to y + * minus one. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \retval 1 if less than or equal to one. + * \retval 0 if greater than one. + */ +BEECRYPTAPI +int mpeqmone(size_t size, const mpw* xdata, const mpw* ydata); + +/*!\fn int mpmsbset(size_t size, const mpw* data) + * \brief This function tests if the most significant bit of a multi-precision + * integer is set. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if set + * \retval 0 if not set + */ +BEECRYPTAPI +int mpmsbset(size_t size, const mpw* data); + +/*!\fn int mplsbset(size_t size, const mpw* data) + * \brief This function tests if the leiast significant bit of a multi-precision + * integer is set. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + * \retval 1 if set + * \retval 0 if not set + */ +BEECRYPTAPI +int mplsbset(size_t size, const mpw* data); + +/*!\fn void mpsetmsb(size_t size, mpw* data) + * \brief This function sets the most significant bit of a multi-precision + * integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpsetmsb(size_t size, mpw* data); + +/*!\fn void mpsetlsb(size_t size, mpw* data) + * \brief This function sets the least significant bit of a multi-precision + * integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpsetlsb(size_t size, mpw* data); + +/*!\fn void mpclrmsb(size_t size, mpw* data) + * \brief This function clears the most significant bit of a multi-precision + * integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpclrmsb(size_t size, mpw* data); + +/*!\fn void mpclrlsb(size_t size, mpw* data) + * \brief This function clears the least significant bit of a multi-precision + * integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpclrlsb(size_t size, mpw* data); + +/*!\fn mpand(size_t size, mpw* xdata, const mpw* ydata) + * \brief This function computes the bit-wise AND of two multi-precision + * integers. Modifies xdata. + * \param size The size of the multi-precision integers. + * \param xdata The multi-precision integer data. + * \param ydata The multi-precision integer data. + */ +BEECRYPTAPI +void mpand(size_t size, mpw* xdata, const mpw* ydata); + +/*!\fn void mpor(size_t size, mpw* xdata, const mpw* ydata) + * \brief This function computes the bit-wise OR of two multi-precision + * integers. Modifies xdata. + * \param size The size of the multi-precision integer. + * \param xdata The multi-precision integer data. + * \param ydata The multi-precision integer data. + */ +BEECRYPTAPI +void mpor(size_t size, mpw* xdata, const mpw* ydata); + +/*!\fn void mpxor(size_t size, mpw* xdata, const mpw* ydata) + * \brief This function computes the bit-wise XOR of two multi-precision + * integers. Modifies xdata. + * \param size The size of the multi-precision integer. + * \param xdata The multi-precision integer data. + * \param ydata The multi-precision integer data. + */ +BEECRYPTAPI +void mpxor(size_t size, mpw* xdata, const mpw* ydata); + +/*!\fn mpnot(size_t size, mpw* data) + * \brief This function flips all bits of a multi-precision integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpnot(size_t size, mpw* data); + +/*!\fn void mpsetw(size_t size, mpw* xdata, mpw y) + * \brief This function sets the value of a multi-precision integer to the + * given word. The given value is copied into the least significant word, + * while the most significant words are zeroed. + * \param size The size of the multi-precision integer. + * \param xdata The first multi-precision integer. + * \param y The multi-precision word. + */ +BEECRYPTAPI +void mpsetw(size_t size, mpw* xdata, mpw y); + +/*!\fn void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function set the value of the first multi-precision integer + * to the second, truncating the most significant words if ysize > xsize, or + * zeroing the most significant words if ysize < xsize. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + */ +void mpsetx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpaddw(size_t size, mpw* xdata, mpw y) + * \brief This function adds one word to a multi-precision integer. + * The performed operation is in pseudocode: x += y. + * \param size The size of the multi-precision integer. + * \param xdata The first multi-precision integer. + * \param y The multi-precision word. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpaddw(size_t size, mpw* xdata, mpw y); + +/*!\fn int mpadd(size_t size, mpw* xdata, const mpw* ydata) + * \brief This function adds two multi-precision integers of equal size. + * The performed operation is in pseudocode: x += y. + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpadd (size_t size, mpw* xdata, const mpw* ydata); + +/*!\fn int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function adds two multi-precision integers of different size. + * The performed operation in pseudocode: x += y. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpaddx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn int mpsubw(size_t size, mpw* xdata, mpw y) + * \brief This function subtracts one word to a multi-precision integer. + * The performed operation in pseudocode: x -= y + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param y The multi-precision word. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpsubw(size_t size, mpw* xdata, mpw y); + +/*!\fn int mpsub(size_t size, mpw* xdata, const mpw* ydata) + * \brief This function subtracts two multi-precision integers of equal size. + * The performed operation in pseudocode: x -= y + * \param size The size of the multi-precision integers. + * \param xdata The first multi-precision integer. + * \param ydata The second multi-precision integer. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpsub (size_t size, mpw* xdata, const mpw* ydata); + +/*!\fn int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function subtracts two multi-precision integers of different + * size. The performed operation in pseudocode: x -= y. + * \param xsize The size of the first multi-precision integer. + * \param xdata The first multi-precision integer. + * \param ysize The size of the second multi-precision integer. + * \param ydata The second multi-precision integer. + * \return The carry-over value of the operation; this value is either 0 or 1. + */ +BEECRYPTAPI +int mpsubx(size_t xsize, mpw* xdata, size_t ysize, const mpw* ydata); + +BEECRYPTAPI +int mpmultwo(size_t size, mpw* data); + +/*!\fn void mpneg(size_t size, mpw* data) + * \brief This function negates a multi-precision integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +void mpneg(size_t size, mpw* data); + +/*!\fn size_t mpsize(size_t size, const mpw* data) + * \brief This function returns the true size of a multi-precision + * integer, after stripping leading zero words. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +size_t mpsize(size_t size, const mpw* data); + +/*!\fn size_t mpbits(size_t size, const mpw* data) + * \brief This function returns the number of significant bits + * in a multi-precision integer. + * \param size The size of the multi-precision integer. + * \param data The multi-precision integer data. + */ +BEECRYPTAPI +size_t mpbits(size_t size, const mpw* data); + +BEECRYPTAPI +size_t mpmszcnt(size_t size, const mpw* data); + +BEECRYPTAPI +size_t mplszcnt(size_t size, const mpw* data); + +BEECRYPTAPI +void mplshift(size_t size, mpw* data, size_t count); + +BEECRYPTAPI +void mprshift(size_t size, mpw* data, size_t count); + +BEECRYPTAPI +size_t mprshiftlsz(size_t size, mpw* data); + +BEECRYPTAPI +size_t mpnorm(size_t size, mpw* data); + +BEECRYPTAPI +void mpdivtwo (size_t size, mpw* data); + +BEECRYPTAPI +void mpsdivtwo(size_t size, mpw* data); + +/*!\fn mpw mpsetmul(size_t size, mpw* result, const mpw* data, mpw y) + * \brief This function performs a multi-precision multiply-setup. + * + * This function is used in the computation of a full multi-precision + * multiplication. By using it we can shave off a few cycles; otherwise we'd + * have to zero the least significant half of the result first and use + * another call to the slightly slower mpaddmul function. + * + * \param size The size of multi-precision integer multiplier. + * \param result The place where result will be accumulated. + * \param data The multi-precision integer multiplier. + * \param y The multiplicand. + * \return The carry-over multi-precision word. + */ +BEECRYPTAPI +mpw mpsetmul (size_t size, mpw* result, const mpw* data, mpw y); + +/*!\fn mpw mpaddmul(size_t size, mpw* result, const mpw* data, mpw y) + * \brief This function performs a mult-precision multiply-accumulate. + * + * This function is used in the computation of a full multi-precision + * multiplication. It computes the product-by-one-word and accumulates it with + * the previous result. + * + * \param size The size of multi-precision integer multiplier. + * \param result The place where result will be accumulated. + * \param data The multi-precision integer multiplier. + * \param y The multiplicand. + * \retval The carry-over multi-precision word. + */ +BEECRYPTAPI +mpw mpaddmul (size_t size, mpw* result, const mpw* data, mpw y); + +/*!\fn void mpaddsqrtrc(size_t size, mpw* result, const mpw* data) + * \brief This function is used in the calculation of a multi-precision + * squaring. + */ +BEECRYPTAPI +void mpaddsqrtrc(size_t size, mpw* result, const mpw* data); + +/*!\fn void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata) + * \brief This function computes a full multi-precision product. + */ +BEECRYPTAPI +void mpmul(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata); + +/*!\fn void mpsqr(mpw* result, size_t size, const mpw* data) + * \brief This function computes a full multi-precision square. + */ +BEECRYPTAPI +void mpsqr(mpw* result, size_t size, const mpw* data); + +BEECRYPTAPI +void mpgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp); + +BEECRYPTAPI +int mpextgcd_w(size_t size, const mpw* xdata, const mpw* ydata, mpw* result, mpw* wksp); + +BEECRYPTAPI +mpw mppndiv(mpw xhi, mpw xlo, mpw y); + +BEECRYPTAPI +void mpmod (mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw*ydata, mpw* wksp); + +BEECRYPTAPI +void mpndivmod(mpw* result, size_t xsize, const mpw* xdata, size_t ysize, const mpw* ydata, mpw* wksp); + +/* + * Output Routines + */ + +BEECRYPTAPI +void mpprint(size_t size, const mpw* data); + +BEECRYPTAPI +void mpprintln(size_t size, const mpw* data); + +BEECRYPTAPI +void mpfprint(FILE* f, size_t size, const mpw* data); + +BEECRYPTAPI +void mpfprintln(FILE* f, size_t size, const mpw* data); + +/* + * Conversion Routines + */ + +BEECRYPTAPI +int os2ip(mpw* idata, size_t isize, const byte* osdata, size_t ossize); + +BEECRYPTAPI +int i2osp(byte* osdata, size_t ossize, const mpw* idata, size_t isize); + +BEECRYPTAPI +int hs2ip(mpw* idata, size_t isize, const char* hsdata, size_t hssize); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h new file mode 100755 index 0000000000..f42e82a80f --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpnumber.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2003 Bob Deblier + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file mpnumber.h + * \brief Multi-precision numbers, headers. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup MP_m + */ + +#ifndef _MPNUMBER_H +#define _MPNUMBER_H + +#include "beecrypt/mp.h" + +#ifdef __cplusplus +# include <iostream> +#endif + +#ifdef __cplusplus +struct BEECRYPTAPI mpnumber +#else +struct _mpnumber +#endif +{ + size_t size; + mpw* data; + +#ifdef __cplusplus + static const mpnumber ZERO; + static const mpnumber ONE; + + mpnumber(); + mpnumber(unsigned int); + mpnumber(const mpnumber&); + ~mpnumber(); + + const mpnumber& operator=(const mpnumber&); + bool operator==(const mpnumber&) const throw (); + bool operator!=(const mpnumber&) const throw (); + + void wipe(); + + size_t bitlength() const throw (); +#endif +}; + +#ifndef __cplusplus +typedef struct _mpnumber mpnumber; +#else +BEECRYPTAPI +std::ostream& operator<<(std::ostream&, const mpnumber&); +/* +BEECRYPTAPI +std::istream& operator>>(std::istream&, mpnumber&); +*/ +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +BEECRYPTAPI +void mpnzero(mpnumber*); +BEECRYPTAPI +void mpnsize(mpnumber*, size_t); +BEECRYPTAPI +void mpninit(mpnumber*, size_t, const mpw*); +BEECRYPTAPI +void mpnfree(mpnumber*); +BEECRYPTAPI +void mpncopy(mpnumber*, const mpnumber*); +BEECRYPTAPI +void mpnwipe(mpnumber*); + +BEECRYPTAPI +void mpnset (mpnumber*, size_t, const mpw*); +BEECRYPTAPI +void mpnsetw (mpnumber*, mpw); + +BEECRYPTAPI +int mpnsetbin(mpnumber*, const byte*, size_t); +BEECRYPTAPI +int mpnsethex(mpnumber*, const char*); + +BEECRYPTAPI +int mpninv(mpnumber*, const mpnumber*, const mpnumber*); + +/*!\brief Truncate the mpnumber to the specified number of (least significant) bits. + */ +BEECRYPTAPI +size_t mpntrbits(mpnumber*, size_t); +BEECRYPTAPI +size_t mpnbits(const mpnumber*); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h new file mode 100755 index 0000000000..7ba66bb5f9 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/mpopt.h @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2003 Bob Deblier + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file mpopt.h + * \brief Multi-precision integer optimization definitions. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup MP_m + */ + +#ifndef _MPOPT_H +#define _MPOPT_H + +#if WIN32 +# if __MWERKS__ && __INTEL__ +# elif defined(_MSC_VER) && defined(_M_IX86) +# define ASM_MPZERO +# define ASM_MPFILL +# define ASM_MPEVEN +# define ASM_MPODD +# define ASM_MPADDW +# define ASM_MPSUBW +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPDIVTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# endif +#endif + +#if defined(__DECC) +# if defined(OPTIMIZE_ALPHA) +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# endif +#endif + +#if defined(__GNUC__) +# if defined(OPTIMIZE_ALPHA) +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_ARM) +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_MPZERO +# define ASM_MPFILL +# define ASM_MPEVEN +# define ASM_MPODD +# define ASM_MPADD +# define ASM_MPADDW +# define ASM_MPSUB +# define ASM_MPSUBW +# define ASM_MPMULTWO +# define ASM_MPDIVTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# define ASM_MPPNDIV +# elif defined(OPTIMIZE_IA64) +# define ASM_MPZERO +# define ASM_MPCOPY +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# elif defined(OPTIMIZE_M68K) +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64) +# define ASM_MPSETMUL +# define ASM_MPADD +# define ASM_MPADDW +# define ASM_MPSUB +# define ASM_MPSUBW +# define ASM_MPMULTWO +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_S390X) +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_SPARCV8) +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_SPARCV8PLUS) +# define ASM_MPADDW +# define ASM_MPSUBW +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_X86_64) +# define ASM_MPZERO +# define ASM_MPFILL +# define ASM_MPEVEN +# define ASM_MPODD +# define ASM_MPADD +# define ASM_MPADDW +# define ASM_MPSUB +# define ASM_MPSUBW +# define ASM_MPDIVTWO +# define ASM_MPMULTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# endif +#endif + +#if defined(__IBMC__) +# if defined(OPTIMIZE_POWERPC) || defined(OPTIMIZE_POWERPC64) +# define ASM_MPSETMUL +# define ASM_MPADDW +# define ASM_MPSUBW +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# endif +#endif + +#if defined(__INTEL_COMPILER) +# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_MPZERO +# define ASM_MPFILL +# define ASM_MPEVEN +# define ASM_MPODD +# define ASM_MPADDW +# define ASM_MPSUBW +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPDIVTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# define ASM_MPPNDIV +# endif +#endif + +#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# if defined(OPTIMIZE_SPARCV8) +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# elif defined(OPTIMIZE_SPARCV8PLUS) +# define ASM_MPADDW +# define ASM_MPSUBW +# define ASM_MPADD +# define ASM_MPSUB +# define ASM_MPMULTWO +# define ASM_MPSETMUL +# define ASM_MPADDMUL +# define ASM_MPADDSQRTRC +# endif +#endif + +#undef ASM_MPZERO +#undef ASM_MPFILL +#undef ASM_MPEVEN +#undef ASM_MPODD +#undef ASM_MPADD +#undef ASM_MPADDW +#undef ASM_MPSUB +#undef ASM_MPSUBW +#undef ASM_MPMULTWO +#undef ASM_MPDIVTWO +#undef ASM_MPSETMUL +#undef ASM_MPADDMUL +#undef ASM_MPADDSQRTRC +#undef ASM_MPPNDIV + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h new file mode 100755 index 0000000000..dbb0e45412 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/rsa.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file rsa.h + * \brief RSA algorithm. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup IF_m IF_rsa_m + */ + +#ifndef _RSA_H +#define _RSA_H + +#include "beecrypt/rsakp.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\fn int rsapub(const mpbarrett* n, const mpnumber* e, const mpnumber* m, mpnumber* c) + * \brief This function performs a raw RSA public key operation. + * + * This function can be used for encryption and verifying. + * + * It performs the following operation: + * \li \f$c=m^{e}\ \textrm{mod}\ n\f$ + * + * \param n The RSA modulus. + * \param e The RSA public exponent. + * \param m The message. + * \param c The ciphertext. + * \retval 0 on success. + * \retval -1 on failure. + */ +BEECRYPTAPI +int rsapub(const mpbarrett* n, const mpnumber* e, + const mpnumber* m, mpnumber* c); + +/*!\fn int rsapri(const mpbarrett* n, const mpnumber* d, const mpnumber* c, mpnumber* m) + * \brief This function performs a raw RSA private key operation. + * + * This function can be used for decryption and signing. + * + * It performs the operation: + * \li \f$m=c^{d}\ \textrm{mod}\ n\f$ + * + * \param n The RSA modulus. + * \param d The RSA private exponent. + * \param c The ciphertext. + * \param m The message. + * \retval 0 on success. + * \retval -1 on failure. + */ +BEECRYPTAPI +int rsapri(const mpbarrett* n, const mpnumber* d, + const mpnumber* c, mpnumber* m); + +/*!\fn int rsapricrt(const mpbarrett* n, const mpbarrett* p, const mpbarrett* q, const mpnumber* dp, const mpnumber* dq, const mpnumber* qi, const mpnumber* c, mpnumber* m) + * + * \brief This function performs a raw RSA private key operation, with + * application of the Chinese Remainder Theorem. + * + * It performs the operation: + * \li \f$j_1=c^{dp}\ \textrm{mod}\ p\f$ + * \li \f$j_2=c^{dq}\ \textrm{mod}\ q\f$ + * \li \f$h=qi \cdot (j_1-j_2)\ \textrm{mod}\ p\f$ + * \li \f$m=j_2+hq\f$ + * + * \param n The RSA modulus. + * \param p The first RSA prime factor. + * \param q The second RSA prime factor. + * \param dp + * \param dq + * \param qi + * \param c The ciphertext. + * \param m The message. + * \retval 0 on success. + * \retval -1 on failure. + */ +BEECRYPTAPI +int rsapricrt(const mpbarrett* n, const mpbarrett* p, const mpbarrett* q, + const mpnumber* dp, const mpnumber* dq, const mpnumber* qi, + const mpnumber* c, mpnumber* m); + +/*!\fn int rsavrfy(const mpbarrett* n, const mpnumber* e, const mpnumber* m, const mpnumber* c) + * \brief This function performs a raw RSA verification. + * + * It verifies if ciphertext \a c was encrypted from cleartext \a m + * with the private key matching the given public key \a (n, e). + * + * \param n The RSA modulus. + * \param e The RSA public exponent. + * \param m The cleartext message. + * \param c The ciphertext message. + * \retval 1 on success. + * \retval 0 on failure. + */ +BEECRYPTAPI +int rsavrfy(const mpbarrett* n, const mpnumber* e, + const mpnumber* m, const mpnumber* c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c new file mode 100755 index 0000000000..fe7c2cd8b4 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.c @@ -0,0 +1,329 @@ +/* + * Copyright (c) 1997, 1998, 1999, 2000, 2001 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file sha1.c + * \brief SHA-1 hash function, as specified by NIST FIPS 180-1. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup HASH_m HASH_sha1_m + */ + +#define BEECRYPT_DLL_EXPORT + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include "beecrypt/sha1.h" + +#if HAVE_ENDIAN_H && HAVE_ASM_BYTEORDER_H +# include <endian.h> +#endif + +#include "beecrypt/endianness.h" + +/*!\addtogroup HASH_sha1_m + * \{ + */ + +static const uint32_t k[4] = { 0x5a827999U, 0x6ed9eba1U, 0x8f1bbcdcU, 0xca62c1d6U }; + +static const uint32_t hinit[5] = { 0x67452301U, 0xefcdab89U, 0x98badcfeU, 0x10325476U, 0xc3d2e1f0U }; + +const hashFunction sha1 = { + "SHA-1", + sizeof(sha1Param), + 64, + 20, + (hashFunctionReset) sha1Reset, + (hashFunctionUpdate) sha1Update, + (hashFunctionDigest) sha1Digest +}; + +int sha1Reset(register sha1Param* p) +{ + memcpy(p->h, hinit, 5 * sizeof(uint32_t)); + memset(p->data, 0, 80 * sizeof(uint32_t)); + #if (MP_WBITS == 64) + mpzero(1, p->length); + #elif (MP_WBITS == 32) + mpzero(2, p->length); + #else + # error + #endif + p->offset = 0; + return 0; +} + +#define SUBROUND1(a, b, c, d, e, w, k) \ + e = ROTL32(a, 5) + ((b&(c^d))^d) + e + w + k; \ + b = ROTR32(b, 2) +#define SUBROUND2(a, b, c, d, e, w, k) \ + e = ROTL32(a, 5) + (b^c^d) + e + w + k; \ + b = ROTR32(b, 2) +#define SUBROUND3(a, b, c, d, e, w, k) \ + e = ROTL32(a, 5) + (((b|c)&d)|(b&c)) + e + w + k; \ + b = ROTR32(b, 2) +#define SUBROUND4(a, b, c, d, e, w, k) \ + e = ROTL32(a, 5) + (b^c^d) + e + w + k; \ + b = ROTR32(b, 2) + +#ifndef ASM_SHA1PROCESS +void sha1Process(sha1Param* sp) +{ + register uint32_t a, b, c, d, e; + register uint32_t *w; + register byte t; + + #if WORDS_BIGENDIAN + w = sp->data + 16; + #else + w = sp->data; + t = 16; + while (t--) + { + register uint32_t temp = swapu32(*w); + *(w++) = temp; + } + #endif + + t = 64; + while (t--) + { + register uint32_t temp = w[-3] ^ w[-8] ^ w[-14] ^ w[-16]; + *(w++) = ROTL32(temp, 1); + } + + w = sp->data; + + a = sp->h[0]; b = sp->h[1]; c = sp->h[2]; d = sp->h[3]; e = sp->h[4]; + + SUBROUND1(a,b,c,d,e,w[ 0],k[0]); + SUBROUND1(e,a,b,c,d,w[ 1],k[0]); + SUBROUND1(d,e,a,b,c,w[ 2],k[0]); + SUBROUND1(c,d,e,a,b,w[ 3],k[0]); + SUBROUND1(b,c,d,e,a,w[ 4],k[0]); + SUBROUND1(a,b,c,d,e,w[ 5],k[0]); + SUBROUND1(e,a,b,c,d,w[ 6],k[0]); + SUBROUND1(d,e,a,b,c,w[ 7],k[0]); + SUBROUND1(c,d,e,a,b,w[ 8],k[0]); + SUBROUND1(b,c,d,e,a,w[ 9],k[0]); + SUBROUND1(a,b,c,d,e,w[10],k[0]); + SUBROUND1(e,a,b,c,d,w[11],k[0]); + SUBROUND1(d,e,a,b,c,w[12],k[0]); + SUBROUND1(c,d,e,a,b,w[13],k[0]); + SUBROUND1(b,c,d,e,a,w[14],k[0]); + SUBROUND1(a,b,c,d,e,w[15],k[0]); + SUBROUND1(e,a,b,c,d,w[16],k[0]); + SUBROUND1(d,e,a,b,c,w[17],k[0]); + SUBROUND1(c,d,e,a,b,w[18],k[0]); + SUBROUND1(b,c,d,e,a,w[19],k[0]); + + SUBROUND2(a,b,c,d,e,w[20],k[1]); + SUBROUND2(e,a,b,c,d,w[21],k[1]); + SUBROUND2(d,e,a,b,c,w[22],k[1]); + SUBROUND2(c,d,e,a,b,w[23],k[1]); + SUBROUND2(b,c,d,e,a,w[24],k[1]); + SUBROUND2(a,b,c,d,e,w[25],k[1]); + SUBROUND2(e,a,b,c,d,w[26],k[1]); + SUBROUND2(d,e,a,b,c,w[27],k[1]); + SUBROUND2(c,d,e,a,b,w[28],k[1]); + SUBROUND2(b,c,d,e,a,w[29],k[1]); + SUBROUND2(a,b,c,d,e,w[30],k[1]); + SUBROUND2(e,a,b,c,d,w[31],k[1]); + SUBROUND2(d,e,a,b,c,w[32],k[1]); + SUBROUND2(c,d,e,a,b,w[33],k[1]); + SUBROUND2(b,c,d,e,a,w[34],k[1]); + SUBROUND2(a,b,c,d,e,w[35],k[1]); + SUBROUND2(e,a,b,c,d,w[36],k[1]); + SUBROUND2(d,e,a,b,c,w[37],k[1]); + SUBROUND2(c,d,e,a,b,w[38],k[1]); + SUBROUND2(b,c,d,e,a,w[39],k[1]); + + SUBROUND3(a,b,c,d,e,w[40],k[2]); + SUBROUND3(e,a,b,c,d,w[41],k[2]); + SUBROUND3(d,e,a,b,c,w[42],k[2]); + SUBROUND3(c,d,e,a,b,w[43],k[2]); + SUBROUND3(b,c,d,e,a,w[44],k[2]); + SUBROUND3(a,b,c,d,e,w[45],k[2]); + SUBROUND3(e,a,b,c,d,w[46],k[2]); + SUBROUND3(d,e,a,b,c,w[47],k[2]); + SUBROUND3(c,d,e,a,b,w[48],k[2]); + SUBROUND3(b,c,d,e,a,w[49],k[2]); + SUBROUND3(a,b,c,d,e,w[50],k[2]); + SUBROUND3(e,a,b,c,d,w[51],k[2]); + SUBROUND3(d,e,a,b,c,w[52],k[2]); + SUBROUND3(c,d,e,a,b,w[53],k[2]); + SUBROUND3(b,c,d,e,a,w[54],k[2]); + SUBROUND3(a,b,c,d,e,w[55],k[2]); + SUBROUND3(e,a,b,c,d,w[56],k[2]); + SUBROUND3(d,e,a,b,c,w[57],k[2]); + SUBROUND3(c,d,e,a,b,w[58],k[2]); + SUBROUND3(b,c,d,e,a,w[59],k[2]); + + SUBROUND4(a,b,c,d,e,w[60],k[3]); + SUBROUND4(e,a,b,c,d,w[61],k[3]); + SUBROUND4(d,e,a,b,c,w[62],k[3]); + SUBROUND4(c,d,e,a,b,w[63],k[3]); + SUBROUND4(b,c,d,e,a,w[64],k[3]); + SUBROUND4(a,b,c,d,e,w[65],k[3]); + SUBROUND4(e,a,b,c,d,w[66],k[3]); + SUBROUND4(d,e,a,b,c,w[67],k[3]); + SUBROUND4(c,d,e,a,b,w[68],k[3]); + SUBROUND4(b,c,d,e,a,w[69],k[3]); + SUBROUND4(a,b,c,d,e,w[70],k[3]); + SUBROUND4(e,a,b,c,d,w[71],k[3]); + SUBROUND4(d,e,a,b,c,w[72],k[3]); + SUBROUND4(c,d,e,a,b,w[73],k[3]); + SUBROUND4(b,c,d,e,a,w[74],k[3]); + SUBROUND4(a,b,c,d,e,w[75],k[3]); + SUBROUND4(e,a,b,c,d,w[76],k[3]); + SUBROUND4(d,e,a,b,c,w[77],k[3]); + SUBROUND4(c,d,e,a,b,w[78],k[3]); + SUBROUND4(b,c,d,e,a,w[79],k[3]); + + sp->h[0] += a; + sp->h[1] += b; + sp->h[2] += c; + sp->h[3] += d; + sp->h[4] += e; +} +#endif + +int sha1Update(sha1Param* sp, const byte* data, size_t size) +{ + register uint32_t proclength; + + #if (MP_WBITS == 64) + mpw add[1]; + mpsetw(1, add, size); + mplshift(1, add, 3); + mpadd(1, sp->length, add); + #elif (MP_WBITS == 32) + mpw add[2]; + mpsetw(2, add, size); + mplshift(2, add, 3); + mpadd(2, sp->length, add); + #else + # error + #endif + + while (size > 0) + { + proclength = ((sp->offset + size) > 64U) ? (64U - sp->offset) : size; + memcpy(((byte *) sp->data) + sp->offset, data, proclength); + size -= proclength; + data += proclength; + sp->offset += proclength; + + if (sp->offset == 64) + { + sha1Process(sp); + sp->offset = 0; + } + } + return 0; +} + +static void sha1Finish(sha1Param* sp) +{ + register byte *ptr = ((byte *) sp->data) + sp->offset++; + + *(ptr++) = 0x80; + + if (sp->offset > 56) + { + while (sp->offset++ < 64) + *(ptr++) = 0; + + sha1Process(sp); + sp->offset = 0; + } + + ptr = ((byte*) sp->data) + sp->offset; + while (sp->offset++ < 56) + *(ptr++) = 0; + + #if WORDS_BIGENDIAN + memcpy(ptr, sp->length, 8); + #else + # if (MP_WBITS == 64) + ptr[0] = (byte)(sp->length[0] >> 56); + ptr[1] = (byte)(sp->length[0] >> 48); + ptr[2] = (byte)(sp->length[0] >> 40); + ptr[3] = (byte)(sp->length[0] >> 32); + ptr[4] = (byte)(sp->length[0] >> 24); + ptr[5] = (byte)(sp->length[0] >> 16); + ptr[6] = (byte)(sp->length[0] >> 8); + ptr[7] = (byte)(sp->length[0] ); + #elif (MP_WBITS == 32) + ptr[0] = (byte)(sp->length[0] >> 24); + ptr[1] = (byte)(sp->length[0] >> 16); + ptr[2] = (byte)(sp->length[0] >> 8); + ptr[3] = (byte)(sp->length[0] ); + ptr[4] = (byte)(sp->length[1] >> 24); + ptr[5] = (byte)(sp->length[1] >> 16); + ptr[6] = (byte)(sp->length[1] >> 8); + ptr[7] = (byte)(sp->length[1] ); + # else + # error + # endif + #endif + + sha1Process(sp); + + sp->offset = 0; +} + +int sha1Digest(sha1Param* sp, byte* data) +{ + sha1Finish(sp); + + #if WORDS_BIGENDIAN + memcpy(data, sp->h, 20); + #else + /* encode 5 integers big-endian style */ + data[ 0] = (byte)(sp->h[0] >> 24); + data[ 1] = (byte)(sp->h[0] >> 16); + data[ 2] = (byte)(sp->h[0] >> 8); + data[ 3] = (byte)(sp->h[0] >> 0); + data[ 4] = (byte)(sp->h[1] >> 24); + data[ 5] = (byte)(sp->h[1] >> 16); + data[ 6] = (byte)(sp->h[1] >> 8); + data[ 7] = (byte)(sp->h[1] >> 0); + data[ 8] = (byte)(sp->h[2] >> 24); + data[ 9] = (byte)(sp->h[2] >> 16); + data[10] = (byte)(sp->h[2] >> 8); + data[11] = (byte)(sp->h[2] >> 0); + data[12] = (byte)(sp->h[3] >> 24); + data[13] = (byte)(sp->h[3] >> 16); + data[14] = (byte)(sp->h[3] >> 8); + data[15] = (byte)(sp->h[3] >> 0); + data[16] = (byte)(sp->h[4] >> 24); + data[17] = (byte)(sp->h[4] >> 16); + data[18] = (byte)(sp->h[4] >> 8); + data[19] = (byte)(sp->h[4] >> 0); + #endif + + sha1Reset(sp); + + return 0; +} + +/*!\} + */ diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h new file mode 100755 index 0000000000..a35c917fdd --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 1997, 1998, 1999, 2000, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file sha1.h + * \brief SHA-1 hash function, headers. + * \author Bob Deblier <bob.deblier@pandora.be> + * \ingroup HASH_m HASH_sha1_m + */ + +#ifndef _SHA1_H +#define _SHA1_H + +#include "beecrypt/beecrypt.h" +#include "beecrypt/sha1opt.h" + +/*!\brief Holds all the parameters necessary for the SHA-1 algorithm. + * \ingroup HASH_sha1_m + */ +#ifdef __cplusplus +struct BEECRYPTAPI sha1Param +#else +struct _sha1Param +#endif +{ + /*!\var h + */ + uint32_t h[5]; + /*!\var data + */ + uint32_t data[80]; + /*!\var length + * \brief Multi-precision integer counter for the bits that have been + * processed so far. + */ + #if (MP_WBITS == 64) + mpw length[1]; + #elif (MP_WBITS == 32) + mpw length[2]; + #else + # error + #endif + /*!\var offset + * \brief Offset into \a data; points to the place where new data will be + * copied before it is processed. + */ + uint32_t offset; +}; + +#ifndef __cplusplus +typedef struct _sha1Param sha1Param; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*!\var sha1 + * \brief Holds the full API description of the SHA-1 algorithm. + */ +extern BEECRYPTAPI const hashFunction sha1; + +/*!\fn void sha1Process(sha1Param* sp) + * \brief This function performs the core of the SHA-1 hash algorithm; it + * processes a block of 64 bytes. + * \param sp The hash function's parameter block. + */ +BEECRYPTAPI +void sha1Process(sha1Param* sp); + +/*!\fn int sha1Reset(sha1Param* sp) + * \brief This function resets the parameter block so that it's ready for a + * new hash. + * \param sp The hash function's parameter block. + * \retval 0 on success. + */ +BEECRYPTAPI +int sha1Reset (sha1Param* sp); + +/*!\fn int sha1Update(sha1Param* sp, const byte* data, size_t size) + * \brief This function should be used to pass successive blocks of data + * to be hashed. + * \param sp The hash function's parameter block. + * \param data + * \param size + * \retval 0 on success. + */ +BEECRYPTAPI +int sha1Update (sha1Param* sp, const byte* data, size_t size); + +/*!\fn int sha1Digest(sha1Param* sp, byte* digest) + * \brief This function finishes the current hash computation and copies + * the digest value into \a digest. + * \param sp The hash function's parameter block. + * \param digest The place to store the 20-byte digest. + * \retval 0 on success. + */ +BEECRYPTAPI +int sha1Digest (sha1Param* sp, byte* digest); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h new file mode 100755 index 0000000000..62ea87718f --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/sha1opt.h @@ -0,0 +1,65 @@ +/* + * sha1opt.h + * + * SHA-1 assembler-optimized routines, header + * + * Copyright (c) 2000, 2003 Virtual Unlimited B.V. + * + * Author: Bob Deblier <bob.deblier@pandora.be> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#ifndef _SHA1OPT_H +#define _SHA1OPT_H + +#include "beecrypt/beecrypt.h" +#include "beecrypt/sha1.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if WIN32 +# if defined(_MSC_VER) && defined(_M_IX86) +# define ASM_SHA1PROCESS +# elif __INTEL__ && __MWERKS__ +# define ASM_SHA1PROCESS +# endif +#endif + +#if defined(__GNUC__) +# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_SHA1PROCESS +# endif +#endif + +#if defined(__INTEL_COMPILER) +# if defined(OPTIMIZE_I386) || defined(OPTIMIZE_I486) || defined(OPTIMIZE_I586) || defined(OPTIMIZE_I686) +# define ASM_SHA1PROCESS +# endif +#endif + +#if defined(__SUNPRO_C) || defined(__SUNPRO_CC) +#endif + +#undef ASM_SHA1PROCESS + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h new file mode 100755 index 0000000000..d578085c29 --- /dev/null +++ b/utils/zenutils/libraries/beecrypt-4.1.2/beecrypt/win.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2000, 2001, 2002 Virtual Unlimited B.V. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +/*!\file win.h + * \brief BeeCrypt API, windows headers. + * \author Bob Deblier <bob.deblier@pandora.be> + */ + +#ifndef _BEECRYPT_WIN_H +#define _BEECRYPT_WIN_H + +#define _REENTRANT + +#if !defined(_WIN32_WINNT) +#define _WIN32_WINNT 0x0400 +#endif + +#include <windows.h> + +#if __MWERKS__ +# if __INTEL__ +# define WORDS_BIGENDIAN 0 +# else +# error Unknown CPU type in MetroWerks CodeWarrior +# endif +#elif defined(_MSC_VER) +# if defined(_M_IX86) +# define WORDS_BIGENDIAN 0 +# define ROTL32(x, s) _rotl(x, s) +# define ROTR32(x, s) _rotr(x, s) +# else +# error Unknown CPU type in Microsoft Visual C +# endif +#else +# error Unknown compiler for WIN32 +#endif + +#if defined(_MSC_VER) || __MWERKS__ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define HAVE_ERRNO_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FCNTL_H 1 +#define HAVE_TIME_H 1 + +#define HAVE_SYS_TYPES_H 0 +#define HAVE_SYS_TIME_H 0 + +#define HAVE_THREAD_H 0 +#define HAVE_SYNCH_H 0 +#define HAVE_PTHREAD_H 0 +#define HAVE_SEMAPHORE_H 0 + +#define HAVE_TERMIO_H 0 +#define HAVE_SYS_AUDIOIO_H 0 +#define HAVE_SYS_IOCTL_H 0 +#define HAVE_SYS_SOUNDCARD_H 0 + +#define HAVE_GETTIMEOFDAY 0 +#define HAVE_GETHRTIME 0 + +#define HAVE_DEV_TTY 0 +#define HAVE_DEV_AUDIO 0 +#define HAVE_DEV_DSP 0 +#define HAVE_DEV_RANDOM 0 +#define HAVE_DEV_URANDOM 0 +#define HAVE_DEV_TTY 0 + +#else +#error Not set up for this compiler +#endif + +#if __MWERKS__ +#define HAVE_SYS_STAT_H 0 + +#define HAVE_LONG_LONG 1 +#define HAVE_UNSIGNED_LONG_LONG 1 + +#define HAVE_64_BIT_INT 1 +#define HAVE_64_BIT_UINT 1 + +typedef char int8_t; +typedef short int16_t; +typedef long int32_t; +typedef long long int64_t; + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned long uint32_t; +typedef unsigned long long uint64_t; + +#elif defined(_MSC_VER) +#define HAVE_SYS_STAT_H 1 + +#define HAVE_LONG_LONG 0 +#define HAVE_UNSIGNED_LONG_LONG 0 + +#define HAVE_64_BIT_INT 1 +#define HAVE_64_BIT_UINT 1 + +typedef signed char int8_t; +typedef signed short int16_t; +typedef signed int int32_t; +typedef signed __int64 int64_t; + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; +typedef unsigned __int64 uint64_t; + +typedef long off_t; + +#endif + +#define MP_WBITS 32U + +typedef HANDLE bc_cond_t; +typedef HANDLE bc_mutex_t; +typedef HANDLE bc_thread_t; + +#endif diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot new file mode 100755 index 0000000000..0663880990 --- /dev/null +++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/GetPot @@ -0,0 +1,2433 @@ +// -*- c++ -*- +// GetPot Version $$Version$$ $$Date$$ +// +// WEBSITE: http://getpot.sourceforge.net +// +// NOTE: The LPGL License for this library is only valid in case that +// it is not used for the production or development of applications +// dedicated to military industry. This is what the author calls +// the 'unofficial peace version of the LPGL'. +// +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as +// published by the Free Software Foundation; either version 2.1 of the +// License, or (at your option) any later version. +// +// This library 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 +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +// USA +// +// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net> +//========================================================================== + +#ifndef __include_guard_GETPOT_H__ +#define __include_guard_GETPOT_H__ + +#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC) +#define strtok_r(a, b, c) strtok(a, b) +#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC + +extern "C" { +// leave the 'extern C' to make it 100% sure to work - +// expecially with older distributions of header files. +#ifndef WIN32 +// this is necessary (depending on OS) +#include <ctype.h> +#endif +#include <stdio.h> +#include <stdarg.h> +#include <assert.h> +} +#include <cmath> +#include <string> +#include <vector> +#include <algorithm> + +#include <fstream> +#include <iostream> // not every compiler distribution includes <iostream> +// // with <fstream> + +typedef std::vector<std::string> STRING_VECTOR; + +#define victorate(TYPE, VARIABLE, ITERATOR) \ + std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \ + for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++) + + +class GetPot { + //-------- + inline void __basic_initialization(); +public: + // (*) constructors, destructor, assignment operator ----------------------- + inline GetPot(); + inline GetPot(const GetPot&); + inline GetPot(const int argc_, char** argv_, + const char* FieldSeparator=0x0); + inline GetPot(const char* FileName, + const char* CommentStart=0x0, const char* CommentEnd=0x0, + const char* FieldSeparator=0x0); + inline ~GetPot(); + inline GetPot& operator=(const GetPot&); + + + // (*) absorbing contents of another GetPot object + inline void absorb(const GetPot& That); + // -- for ufo detection: recording requested arguments, options etc. + inline void clear_requests(); + inline void disable_request_recording() { __request_recording_f = false; } + inline void enable_request_recording() { __request_recording_f = true; } + + // (*) direct access to command line arguments ----------------------------- + inline const std::string operator[](unsigned Idx) const; + inline int get(unsigned Idx, int Default) const; + inline double get(unsigned Idx, const double& Default) const; + inline const std::string get(unsigned Idx, const char* Default) const; + inline unsigned size() const; + + // (*) flags --------------------------------------------------------------- + inline bool options_contain(const char* FlagList) const; + inline bool argument_contains(unsigned Idx, const char* FlagList) const; + + // (*) variables ----------------------------------------------------------- + // -- scalar values + inline int operator()(const char* VarName, int Default) const; + inline double operator()(const char* VarName, const double& Default) const; + inline const std::string operator()(const char* VarName, const char* Default) const; + // -- vectors + inline int operator()(const char* VarName, int Default, unsigned Idx) const; + inline double operator()(const char* VarName, const double& Default, unsigned Idx) const; + inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const; + + // -- setting variables + // i) from outside of GetPot (considering prefix etc.) + // ii) from inside, use '__set_variable()' below + inline void set(const char* VarName, const char* Value, const bool Requested = true); + inline void set(const char* VarName, const double& Value, const bool Requested = true); + inline void set(const char* VarName, const int Value, const bool Requested = true); + + inline unsigned vector_variable_size(const char* VarName) const; + inline STRING_VECTOR get_variable_names() const; + inline STRING_VECTOR get_section_names() const; + + + // (*) cursor oriented functions ------------------------------------------- + inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); } + inline bool search_failed() const { return search_failed_f; } + + // -- enable/disable search for an option in loop + inline void disable_loop() { search_loop_f = false; } + inline void enable_loop() { search_loop_f = true; } + + // -- reset cursor to position '1' + inline void reset_cursor(); + inline void init_multiple_occurrence(); + + // -- search for a certain option and set cursor to position + inline bool search(const char* option); + inline bool search(unsigned No, const char* P, ...); + // -- get argument at cursor++ + inline int next(int Default); + inline double next(const double& Default); + inline const std::string next(const char* Default); + // -- search for option and get argument at cursor++ + inline int follow(int Default, const char* Option); + inline double follow(const double& Default, const char* Option); + inline const std::string follow(const char* Default, const char* Option); + // -- search for one of the given options and get argument that follows it + inline int follow(int Default, unsigned No, const char* Option, ...); + inline double follow(const double& Default, unsigned No, const char* Option, ...); + inline const std::string follow(const char* Default, unsigned No, const char* Option, ...); + // -- lists of nominuses following an option + inline std::vector<std::string> nominus_followers(const char* Option); + inline std::vector<std::string> nominus_followers(unsigned No, ...); + + // -- directly followed arguments + inline int direct_follow(int Default, const char* Option); + inline double direct_follow(const double& Default, const char* Option); + inline const std::string direct_follow(const char* Default, const char* Option); + + inline std::vector<std::string> string_tails(const char* StartString); + inline std::vector<int> int_tails(const char* StartString, const int Default = 1); + inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0); + + // (*) nominus arguments --------------------------------------------------- + inline STRING_VECTOR nominus_vector() const; + inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); } + inline std::string next_nominus(); + + // (*) unidentified flying objects ----------------------------------------- + inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const; + inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const; + inline STRING_VECTOR unidentified_arguments() const; + + inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const; + inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const; + inline STRING_VECTOR unidentified_options() const; + + inline std::string unidentified_flags(const char* Known, + int ArgumentNumber /* =-1 */) const; + + inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const; + inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const; + inline STRING_VECTOR unidentified_variables() const; + + inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const; + inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const; + inline STRING_VECTOR unidentified_sections() const; + + inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const; + inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const; + inline STRING_VECTOR unidentified_nominuses() const; + + // (*) output -------------------------------------------------------------- + inline int print() const; + +private: + // (*) Type Declaration ---------------------------------------------------- + struct variable { + //----------- + // Variable to be specified on the command line or in input files. + // (i.e. of the form var='12 312 341') + + // -- constructors, destructors, assignment operator + variable(); + variable(const variable&); + variable(const char* Name, const char* Value, const char* FieldSeparator); + ~variable(); + variable& operator=(const variable& That); + + void take(const char* Value, const char* FieldSeparator); + + // -- get a specific element in the string vector + // (return 0 if not present) + const std::string* get_element(unsigned Idx) const; + + // -- data memebers + std::string name; // identifier of variable + STRING_VECTOR value; // value of variable stored in vector + std::string original; // value of variable as given on command line + }; + + // (*) member variables -------------------------------------------------------------- + std::string prefix; // prefix automatically added in queries + std::string section; // (for dollar bracket parsing) + STRING_VECTOR section_list; // list of all parsed sections + // -- argument vector + STRING_VECTOR argv; // vector of command line arguments stored as strings + unsigned cursor; // cursor for argv + bool search_loop_f; // shall search start at beginning after + // // reaching end of arg array ? + bool search_failed_f; // flag indicating a failed search() operation + // // (e.g. next() functions react with 'missed') + + // -- nominus vector + int nominus_cursor; // cursor for nominus_pointers + std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments + + // -- variables + // (arguments of the form "variable=value") + std::vector<variable> variables; + + // -- comment delimiters + std::string _comment_start; + std::string _comment_end; + + // -- field separator (separating elements of a vector) + std::string _field_separator; + + // -- some functions return a char pointer to a temporarily existing string + // this container makes them 'available' until the getpot object is destroyed. + std::vector<char*> __internal_string_container; + + // -- keeping track about arguments that are requested, so that the UFO detection + // can be simplified + STRING_VECTOR _requested_arguments; + STRING_VECTOR _requested_variables; + STRING_VECTOR _requested_sections; + + bool __request_recording_f; // speed: request recording can be turned off + + // -- if an argument is requested record it and the 'tag' the section branch to which + // it belongs. Caution: both functions mark the sections as 'tagged'. + void __record_argument_request(const std::string& Arg); + void __record_variable_request(const std::string& Arg); + + // (*) helper functions ---------------------------------------------------- + // set variable from inside GetPot (no prefix considered) + inline void __set_variable(const char* VarName, const char* Value); + + // -- produce three basic data vectors: + // - argument vector + // - nominus vector + // - variable dictionary + inline void __parse_argument_vector(const STRING_VECTOR& ARGV); + + // -- helpers for argument list processing + // * search for a variable in 'variables' array + inline const variable* __find_variable(const char*) const; + // * support finding directly followed arguments + inline const char* __match_starting_string(const char* StartString); + // * support search for flags in a specific argument + inline bool __check_flags(const std::string& Str, const char* FlagList) const; + // * type conversion if possible + inline int __convert_to_type(const std::string& String, int Default) const; + inline double __convert_to_type(const std::string& String, double Default) const; + // * prefix extraction + const std::string __get_remaining_string(const std::string& String, + const std::string& Start) const; + // * search for a specific string + inline bool __search_string_vector(const STRING_VECTOR& Vec, + const std::string& Str) const; + + // -- helpers to parse input file + // create an argument vector based on data found in an input file, i.e.: + // 1) delete comments (in between '_comment_start' '_comment_end') + // 2) contract assignment expressions, such as + // my-variable = '007 J. B.' + // into + // my-variable='007 J. B.' + // 3) interprete sections like '[../my-section]' etc. + inline void __skip_whitespace(std::istream& istr); + inline const std::string __get_next_token(std::istream& istr); + inline const std::string __get_string(std::istream& istr); + inline const std::string __get_until_closing_bracket(std::istream& istr); + + inline STRING_VECTOR __read_in_stream(std::istream& istr); + inline STRING_VECTOR __read_in_file(const char* FileName); + inline std::string __process_section_label(const std::string& Section, + STRING_VECTOR& section_stack); + + // -- dollar bracket expressions + std::string __DBE_expand_string(const std::string str); + std::string __DBE_expand(const std::string str); + const GetPot::variable* __DBE_get_variable(const std::string str); + STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber); + + std::string __double2string(const double& Value) const { + // -- converts a double integer into a string + char* tmp = new char[128]; +#ifndef WIN32 + snprintf(tmp, (int)sizeof(char)*128, "%e", Value); +#else + _snprintf(tmp, sizeof(char)*128, "%e", Value); +#endif + std::string result(tmp); + delete [] tmp; + return result; + } + + std::string __int2string(const int& Value) const { + // -- converts an integer into a string + char* tmp = new char[128]; +#ifndef WIN32 + snprintf(tmp, (int)sizeof(char)*128, "%i", Value); +#else + _snprintf(tmp, sizeof(char)*128, "%i", Value); +#endif + std::string result(tmp); + delete [] tmp; + return result; + } + + STRING_VECTOR __get_section_tree(const std::string& FullPath) { + // -- cuts a variable name into a tree of sub-sections. this is requested for recording + // requested sections when dealing with 'ufo' detection. + STRING_VECTOR result; + const char* Start = FullPath.c_str(); + + for(char *p = (char*)Start; *p ; p++) { + if( *p == '/' ) { + *p = '\0'; // set terminating zero for convinience + const std::string Section = Start; + *p = '/'; // reset slash at place + result.push_back(Section); + } + } + + return result; + } +}; + + +/////////////////////////////////////////////////////////////////////////////// +// (*) constructors, destructor, assignment operator +//............................................................................. +// +inline void +GetPot::__basic_initialization() +{ + cursor = 0; nominus_cursor = -1; + search_failed_f = true; search_loop_f = true; + prefix = ""; section = ""; + + // automatic request recording for later ufo detection + __request_recording_f = true; + + // comment start and end strings + _comment_start = std::string("#"); + _comment_end = std::string("\n"); + + // default: separate vector elements by whitespaces + _field_separator = " \t\n"; +} + +inline +GetPot::GetPot() +{ + __basic_initialization(); + + STRING_VECTOR _apriori_argv; + _apriori_argv.push_back(std::string("Empty")); + __parse_argument_vector(_apriori_argv); +} + +inline +GetPot::GetPot(const int argc_, char ** argv_, + const char* FieldSeparator /* =0x0 */) + // leave 'char**' non-const to honor less capable compilers ... +{ + // TODO: Ponder over the problem when the argument list is of size = 0. + // This is 'sabotage', but it can still occur if the user specifies + // it himself. + assert(argc_ >= 1); + __basic_initialization(); + + // if specified -> overwrite default string + if( FieldSeparator ) _field_separator = std::string(FieldSeparator); + + // -- make an internal copy of the argument list: + STRING_VECTOR _apriori_argv; + // -- for the sake of clarity: we do want to include the first argument in the argument vector ! + // it will not be a nominus argument, though. This gives us a minimun vector size of one + // which facilitates error checking in many functions. Also the user will be able to + // retrieve the name of his application by "get[0]" + _apriori_argv.push_back(std::string(argv_[0])); + int i=1; + for(; i<argc_; ++i) { + std::string tmp(argv_[i]); // recall the problem with temporaries, + _apriori_argv.push_back(tmp); // reference counting in arguement lists ... + } + __parse_argument_vector(_apriori_argv); +} + + +inline +GetPot::GetPot(const char* FileName, + const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */, + const char* FieldSeparator/* = 0x0 */) +{ + __basic_initialization(); + + // if specified -> overwrite default strings + if( CommentStart ) _comment_start = std::string(CommentStart); + if( CommentEnd ) _comment_end = std::string(CommentEnd); + if( FieldSeparator ) _field_separator = FieldSeparator; + + STRING_VECTOR _apriori_argv; + // -- file name is element of argument vector, however, it is not parsed for + // variable assignments or nominuses. + _apriori_argv.push_back(std::string(FileName)); + + STRING_VECTOR args = __read_in_file(FileName); + _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end()); + __parse_argument_vector(_apriori_argv); +} + +inline +GetPot::GetPot(const GetPot& That) +{ GetPot::operator=(That); } + +inline +GetPot::~GetPot() +{ + // may be some return strings had to be created, delete now ! + victorate(char*, __internal_string_container, it) + delete [] *it; +} + +inline GetPot& +GetPot::operator=(const GetPot& That) +{ + if (&That == this) return *this; + + _comment_start = That._comment_start; + _comment_end = That._comment_end; + argv = That.argv; + variables = That.variables; + prefix = That.prefix; + + cursor = That.cursor; + nominus_cursor = That.nominus_cursor; + search_failed_f = That.search_failed_f; + + idx_nominus = That.idx_nominus; + search_loop_f = That.search_loop_f; + + return *this; +} + + +inline void +GetPot::absorb(const GetPot& That) +{ + if (&That == this) return; + + STRING_VECTOR __tmp(That.argv); + + __tmp.erase(__tmp.begin()); + + __parse_argument_vector(__tmp); +} + +inline void +GetPot::clear_requests() +{ + _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end()); + _requested_variables.erase(_requested_variables.begin(), _requested_variables.end()); + _requested_sections.erase(_requested_sections.begin(), _requested_sections.end()); +} + +inline void +GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV) +{ + if( ARGV.size() == 0 ) return; + + // build internal databases: + // 1) array with no-minus arguments (usually used as filenames) + // 2) variable assignments: + // 'variable name' '=' number | string + STRING_VECTOR section_stack; + STRING_VECTOR::const_iterator it = ARGV.begin(); + + + section = ""; + + // -- do not parse the first argument, so that it is not interpreted a s a nominus or so. + argv.push_back(*it); + ++it; + + // -- loop over remaining arguments + unsigned i=1; + for(; it != ARGV.end(); ++it, ++i) { + std::string arg = *it; + + if( arg.length() == 0 ) continue; + + // -- [section] labels + if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) { + + // (*) sections are considered 'requested arguments' + if( __request_recording_f ) _requested_arguments.push_back(arg); + + const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2)); + section = __process_section_label(Name, section_stack); + // new section --> append to list of sections + if( find(section_list.begin(), section_list.end(), section) == section_list.end() ) + if( section.length() != 0 ) section_list.push_back(section); + argv.push_back(arg); + } + else { + arg = section + __DBE_expand_string(arg); + argv.push_back(arg); + } + + // -- separate array for nominus arguments + if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i)); + + // -- variables: does arg contain a '=' operator ? + const char* p = arg.c_str(); + for(; *p ; p++) { + if( *p == '=' ) { + // (*) record for later ufo detection + // arguments carriying variables are always treated as 'requested' arguments. + // as a whole! That is 'x=4712' is considered a requested argument. + // + // unrequested variables have to be detected with the ufo-variable + // detection routine. + if( __request_recording_f ) _requested_arguments.push_back(arg); + + // set terminating 'zero' to treat first part as single string + // => arg (from start to 'p') = Name of variable + // p+1 (until terminating zero) = value of variable + char* o = (char*)p++; + *o = '\0'; // set temporary terminating zero + // __set_variable(...) + // calls __find_variable(...) which registers the search + // temporarily disable this + const bool tmp = __request_recording_f; + __request_recording_f = false; + __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest + __request_recording_f = tmp; + *o = '='; // reset the original '=' + break; + } + } + } +} + + +inline STRING_VECTOR +GetPot::__read_in_file(const char* FileName) +{ + std::ifstream i(FileName); + if( ! i ) return STRING_VECTOR(); + // argv[0] == the filename of the file that was read in + return __read_in_stream(i); +} + +inline STRING_VECTOR +GetPot::__read_in_stream(std::istream& istr) +{ + STRING_VECTOR brute_tokens; + while(istr) { + __skip_whitespace(istr); + const std::string Token = __get_next_token(istr); + if( Token.length() == 0 || Token[0] == EOF) break; + brute_tokens.push_back(Token); + } + + // -- reduce expressions of token1'='token2 to a single + // string 'token1=token2' + // -- copy everything into 'argv' + // -- arguments preceded by something like '[' name ']' (section) + // produce a second copy of each argument with a prefix '[name]argument' + unsigned i1 = 0; + unsigned i2 = 1; + unsigned i3 = 2; + + STRING_VECTOR arglist; + while( i1 < brute_tokens.size() ) { + const std::string& SRef = brute_tokens[i1]; + // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef' + // note: java.lang.String: substring(a,b) = from a to b-1 + // C++ string: substr(a,b) = from a to a + b + if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) { + if( i3 >= brute_tokens.size() ) + arglist.push_back(brute_tokens[i1] + brute_tokens[i2]); + else + arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]); + i1 = i3+1; i2 = i3+2; i3 = i3+3; + continue; + } + else { + arglist.push_back(SRef); + i1=i2; i2=i3; i3++; + } + } + return arglist; +} + +inline void +GetPot::__skip_whitespace(std::istream& istr) + // find next non-whitespace while deleting comments +{ + int tmp = istr.get(); + do { + // -- search a non whitespace + while( isspace(tmp) ) { + tmp = istr.get(); + if( ! istr ) return; + } + + // -- look if characters match the comment starter string + const std::istream::pos_type Pos = istr.tellg(); + unsigned i=0; + for(; i<_comment_start.length() ; ++i) { + if( tmp != _comment_start[i] ) { + istr.seekg(Pos); + // -- one step more backwards, since 'tmp' already at non-whitespace + istr.unget(); + return; + } + tmp = istr.get(); + if( ! istr ) { istr.unget(); return; } + } + // 'tmp' contains last character of _comment_starter + + // -- comment starter found -> search for comment ender + unsigned match_no=0; + while(1+1 == 2) { + tmp = istr.get(); + if( ! istr ) { istr.unget(); return; } + + if( tmp == _comment_end[match_no] ) { + match_no++; + if( match_no == _comment_end.length() ) { + istr.unget(); + break; // shuffle more whitespace, end of comment found + } + } + else + match_no = 0; + } + + tmp = istr.get(); + + } while( istr ); + istr.unget(); +} + +inline const std::string +GetPot::__get_next_token(std::istream& istr) + // get next concatinates string token. consider quotes that embrace + // whitespaces +{ + std::string token; + int tmp = 0; + int last_letter = 0; + while(1+1 == 2) { + last_letter = tmp; tmp = istr.get(); + if( tmp == EOF + || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) { + return token; + } + else if( tmp == '\'' && last_letter != '\\' ) { + // QUOTES: un-backslashed quotes => it's a string + token += __get_string(istr); + continue; + } + else if( tmp == '{' && last_letter == '$') { + token += '{' + __get_until_closing_bracket(istr); + continue; + } + else if( tmp == '$' && last_letter == '\\') { + token += tmp; tmp = 0; // so that last_letter will become = 0, not '$'; + continue; + } + else if( tmp == '\\' && last_letter != '\\') + continue; // don't append un-backslashed backslashes + token += tmp; + } +} + +inline const std::string +GetPot::__get_string(std::istream& istr) + // parse input until next matching ' +{ + std::string str; + int tmp = 0; + int last_letter = 0; + while(1 + 1 == 2) { + last_letter = tmp; tmp = istr.get(); + if( tmp == EOF) return str; + // un-backslashed quotes => it's the end of the string + else if( tmp == '\'' && last_letter != '\\') return str; + else if( tmp == '\\' && last_letter != '\\') continue; // don't append + + str += tmp; + } +} + +inline const std::string +GetPot::__get_until_closing_bracket(std::istream& istr) + // parse input until next matching } +{ + std::string str = ""; + int tmp = 0; + int last_letter = 0; + int brackets = 1; + while(1 + 1 == 2) { + last_letter = tmp; tmp = istr.get(); + if( tmp == EOF) return str; + else if( tmp == '{' && last_letter == '$') brackets += 1; + else if( tmp == '}') { + brackets -= 1; + // un-backslashed brackets => it's the end of the string + if( brackets == 0) return str + '}'; + else if( tmp == '\\' && last_letter != '\\') + continue; // do not append an unbackslashed backslash + } + str += tmp; + } +} + +inline std::string +GetPot::__process_section_label(const std::string& Section, + STRING_VECTOR& section_stack) +{ + std::string sname = Section; + // 1) subsection of actual section ('./' prefix) + if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) { + sname = sname.substr(2); + } + // 2) subsection of parent section ('../' prefix) + else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) { + do { + if( section_stack.end() != section_stack.begin() ) + section_stack.pop_back(); + sname = sname.substr(3); + } while( sname.substr(0, 3) == "../" ); + } + // 3) subsection of the root-section + else { + section_stack.erase(section_stack.begin(), section_stack.end()); + // [] => back to root section + } + + if( sname != "" ) { + // parse section name for 'slashes' + unsigned i=0; + while( i < sname.length() ) { + if( sname[i] == '/' ) { + section_stack.push_back(sname.substr(0,i)); + if( i+1 < sname.length()-1 ) + sname = sname.substr(i+1); + i = 0; + } + else + ++i; + } + section_stack.push_back(sname); + } + std::string section = ""; + if( section_stack.size() != 0 ) { + victorate(std::string, section_stack, it) + section += *it + "/"; + } + return section; +} + + +// convert string to DOUBLE, if not possible return Default +inline double +GetPot::__convert_to_type(const std::string& String, double Default) const +{ + double tmp; + if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default; + return tmp; +} + +// convert string to INT, if not possible return Default +inline int +GetPot::__convert_to_type(const std::string& String, int Default) const +{ + // NOTE: intermediate results may be floating points, so that the string + // may look like 2.0e1 (i.e. float format) => use float conversion + // in any case. + return (int)__convert_to_type(String, (double)Default); +} + +////////////////////////////////////////////////////////////////////////////// +// (*) cursor oriented functions +//............................................................................. +inline const std::string +GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const + // Checks if 'String' begins with 'Start' and returns the remaining String. + // Returns None if String does not begin with Start. +{ + if( Start == "" ) return String; + // note: java.lang.String: substring(a,b) = from a to b-1 + // C++ string: substr(a,b) = from a to a + b + if( String.find(Start) == 0 ) return String.substr(Start.length()); + else return ""; +} + +// -- search for a certain argument and set cursor to position +inline bool +GetPot::search(const char* Option) +{ + unsigned OldCursor = cursor; + const std::string SearchTerm = prefix + Option; + + // (*) record requested arguments for later ufo detection + __record_argument_request(SearchTerm); + + if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1; + search_failed_f = true; + + // (*) first loop from cursor position until end + unsigned c = cursor; + for(; c < argv.size(); c++) { + if( argv[c] == SearchTerm ) + { cursor = c; search_failed_f = false; return true; } + } + if( ! search_loop_f ) return false; + + // (*) second loop from 0 to old cursor position + for(c = 1; c < OldCursor; c++) { + if( argv[c] == SearchTerm ) + { cursor = c; search_failed_f = false; return true; } + } + // in case nothing is found the cursor stays where it was + return false; +} + + +inline bool +GetPot::search(unsigned No, const char* P, ...) +{ + // (*) recording the requested arguments happens in subroutine 'search' + if( No == 0 ) return false; + + // search for the first argument + if( search(P) == true ) return true; + + // start interpreting variable argument list + va_list ap; + va_start(ap, P); + unsigned i = 1; + for(; i < No; ++i) { + char* Opt = va_arg(ap, char *); + if( search(Opt) == true ) break; + } + + if( i < No ) { + ++i; + // loop was left before end of array --> hit but + // make sure that the rest of the search terms is marked + // as requested. + for(; i < No; ++i) { + char* Opt = va_arg(ap, char *); + // (*) record requested arguments for later ufo detection + __record_argument_request(Opt); + } + va_end(ap); + return true; + } + + va_end(ap); + // loop was left normally --> no hit + return false; +} + +inline void +GetPot::reset_cursor() +{ search_failed_f = false; cursor = 0; } + +inline void +GetPot::init_multiple_occurrence() +{ disable_loop(); reset_cursor(); } +/////////////////////////////////////////////////////////////////////////////// +// (*) direct access to command line arguments +//............................................................................. +// +inline const std::string +GetPot::operator[](unsigned idx) const +{ return idx < argv.size() ? argv[idx] : ""; } + +inline int +GetPot::get(unsigned Idx, int Default) const +{ + if( Idx >= argv.size() ) return Default; + return __convert_to_type(argv[Idx], Default); +} + +inline double +GetPot::get(unsigned Idx, const double& Default) const +{ + if( Idx >= argv.size() ) return Default; + return __convert_to_type(argv[Idx], Default); +} + +inline const std::string +GetPot::get(unsigned Idx, const char* Default) const +{ + if( Idx >= argv.size() ) return Default; + else return argv[Idx]; +} + +inline unsigned +GetPot::size() const +{ return static_cast<unsigned int>(argv.size()); } + + +// -- next() function group +inline int +GetPot::next(int Default) +{ + if( search_failed_f ) return Default; + cursor++; + if( cursor >= argv.size() ) + { cursor = static_cast<unsigned int>(argv.size()); return Default; } + + // (*) record requested argument for later ufo detection + __record_argument_request(argv[cursor]); + + const std::string Remain = __get_remaining_string(argv[cursor], prefix); + + return Remain != "" ? __convert_to_type(Remain, Default) : Default; +} + +inline double +GetPot::next(const double& Default) +{ + if( search_failed_f ) return Default; + cursor++; + + if( cursor >= argv.size() ) + { cursor = static_cast<unsigned int>(argv.size()); return Default; } + + // (*) record requested argument for later ufo detection + __record_argument_request(argv[cursor]); + + std::string Remain = __get_remaining_string(argv[cursor], prefix); + + return Remain != "" ? __convert_to_type(Remain, Default) : Default; +} + +inline const std::string +GetPot::next(const char* Default) +{ + if( search_failed_f ) return Default; + cursor++; + + if( cursor >= argv.size() ) + { cursor = static_cast<unsigned int>(argv.size()); return Default; } + + // (*) record requested argument for later ufo detection + __record_argument_request(argv[cursor]); + + const std::string Remain = __get_remaining_string(argv[cursor], prefix); + + if( Remain == "" ) return Default; + + + // (*) function returns a pointer to a char array (inside Remain) + // this array will be deleted, though after this function call. + // To ensure propper functioning, create a copy inside *this + // object and only delete it, when *this is deleted. + char* result = new char[Remain.length()+1]; + strncpy(result, Remain.c_str(), Remain.length()+1); + + // store the created string internally, delete if when object deleted + __internal_string_container.push_back(result); + + return result; +} + +// -- follow() function group +// distinct option to be searched for +inline int +GetPot::follow(int Default, const char* Option) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( search(Option) == false ) return Default; + return next(Default); +} + +inline double +GetPot::follow(const double& Default, const char* Option) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( search(Option) == false ) return Default; + return next(Default); +} + +inline const std::string +GetPot::follow(const char* Default, const char* Option) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( search(Option) == false ) return Default; + return next(Default); +} + +// -- second follow() function group +// multiple option to be searched for +inline int +GetPot::follow(int Default, unsigned No, const char* P, ...) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( No == 0 ) return Default; + if( search(P) == true ) return next(Default); + + va_list ap; + va_start(ap, P); + unsigned i=1; + for(; i<No; ++i) { + char* Opt = va_arg(ap, char *); + if( search(Opt) == true ) { + va_end(ap); + return next(Default); + } + } + va_end(ap); + return Default; +} + +inline double +GetPot::follow(const double& Default, unsigned No, const char* P, ...) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( No == 0 ) return Default; + if( search(P) == true ) return next(Default); + + va_list ap; + va_start(ap, P); + for(unsigned i=1; i<No; ++i) { + char* Opt = va_arg(ap, char *); + if( search(Opt) == true ) { + va_end(ap); + return next(Default); + } + } + va_end(ap); + return Default; +} + +inline const std::string +GetPot::follow(const char* Default, unsigned No, const char* P, ...) +{ + // (*) record requested of argument is entirely handled in 'search()' and 'next()' + if( No == 0 ) return Default; + if( search(P) == true ) return next(Default); + + va_list ap; + va_start(ap, P); + unsigned i=1; + for(; i<No; ++i) { + char* Opt = va_arg(ap, char *); + if( search(Opt) == true ) { + va_end(ap); + return next(Default); + } + } + va_end(ap); + return Default; +} + + +/////////////////////////////////////////////////////////////////////////////// +// (*) lists of nominus following an option +//............................................................................. +// +inline std::vector<std::string> +GetPot::nominus_followers(const char* Option) +{ + std::vector<std::string> result_list; + if( search(Option) == false ) return result_list; + while( 1 + 1 == 2 ) { + ++cursor; + if( cursor >= argv.size() ) { + cursor = argv.size() - 1; + return result_list; + } + if( argv[cursor].length() >= 1 ) { + if( argv[cursor][0] == '-' ) { + return result_list; + } + // -- record for later ufo-detection + __record_argument_request(argv[cursor]); + // -- append to the result list + result_list.push_back(argv[cursor]); + } + } +} + +inline std::vector<std::string> +GetPot::nominus_followers(unsigned No, ...) +{ + std::vector<std::string> result_list; + // (*) record requested of argument is entirely handled in 'search()' + // and 'nominus_followers()' + if( No == 0 ) return result_list; + + va_list ap; + va_start(ap, No); + for(unsigned i=0; i<No; ++i) { + char* Option = va_arg(ap, char *); + std::vector<std::string> tmp = nominus_followers(Option); + result_list.insert(result_list.end(), tmp.begin(), tmp.end()); + + // std::cerr << "option = '" << Option << "'" << std::endl; + // std::cerr << "length = " << tmp.size() << std::endl; + // std::cerr << "new result list = <"; + // for(std::vector<std::string>::const_iterator it = result_list.begin(); + // it != result_list.end(); ++it) + // std::cerr << *it << ", "; + // std::cerr << ">\n"; + } + va_end(ap); + return result_list; +} + + +/////////////////////////////////////////////////////////////////////////////// +// (*) directly connected options +//............................................................................. +// +inline int +GetPot::direct_follow(int Default, const char* Option) +{ + const char* FollowStr = __match_starting_string(Option); + if( FollowStr == 0x0 ) return Default; + + // (*) record requested of argument for later ufo-detection + __record_argument_request(std::string(Option) + FollowStr); + + if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); + return __convert_to_type(FollowStr, Default); +} + +inline double +GetPot::direct_follow(const double& Default, const char* Option) +{ + const char* FollowStr = __match_starting_string(Option); + if( FollowStr == 0 ) return Default; + + // (*) record requested of argument for later ufo-detection + __record_argument_request(std::string(Option) + FollowStr); + + if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); + return __convert_to_type(FollowStr, Default); +} + +inline const std::string +GetPot::direct_follow(const char* Default, const char* Option) +{ + if( search_failed_f ) return Default; + const char* FollowStr = __match_starting_string(Option); + if( FollowStr == 0 ) return Default; + + // (*) record requested of argument for later ufo-detection + if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr); + + if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size()); + return std::string(FollowStr); +} + +inline std::vector<std::string> +GetPot::string_tails(const char* StartString) +{ + std::vector<std::string> result; + const unsigned N = static_cast<unsigned int>(strlen(StartString)); + + std::vector<std::string>::iterator it = argv.begin(); + + unsigned idx = 0; + while( it != argv.end() ) { + // (*) does start string match the given option? + // NO -> goto next option + if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } + + // append the found tail to the result vector + result.push_back((*it).substr(N)); + + // adapt the nominus vector + std::vector<unsigned>::iterator nit = idx_nominus.begin(); + for(; nit != idx_nominus.end(); ++nit) { + if( *nit == idx ) { + idx_nominus.erase(nit); + for(; nit != idx_nominus.end(); ++nit) *nit -= 1; + break; + } + } + + // erase the found option + argv.erase(it); + + // 100% safe solution: set iterator back to the beginning. + // (normally, 'it--' would be enough, but who knows how the + // iterator is implemented and .erase() definitely invalidates + // the current iterator position. + if( argv.empty() ) break; + it = argv.begin(); + } + cursor = 0; + nominus_cursor = -1; + return result; +} + +inline std::vector<int> +GetPot::int_tails(const char* StartString, const int Default /* = -1 */) +{ + std::vector<int> result; + const unsigned N = static_cast<unsigned int>(strlen(StartString)); + + std::vector<std::string>::iterator it = argv.begin(); + + unsigned idx = 0; + while( it != argv.end() ) { + // (*) does start string match the given option? + // NO -> goto next option + if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } + + // append the found tail to the result vector + result.push_back(__convert_to_type((*it).substr(N), Default)); + + // adapt the nominus vector + std::vector<unsigned>::iterator nit = idx_nominus.begin(); + for(; nit != idx_nominus.end(); ++nit) { + if( *nit == idx ) { + idx_nominus.erase(nit); + for(; nit != idx_nominus.end(); ++nit) *nit -= 1; + break; + } + } + + // erase the found option + argv.erase(it); + + // 100% safe solution: set iterator back to the beginning. + // (normally, 'it--' would be enough, but who knows how the + // iterator is implemented and .erase() definitely invalidates + // the current iterator position. + if( argv.empty() ) break; + it = argv.begin(); + } + cursor = 0; + nominus_cursor = -1; + return result; +} + +inline std::vector<double> +GetPot::double_tails(const char* StartString, + const double Default /* = -1.0 */) +{ + std::vector<double> result; + const unsigned N = static_cast<unsigned int>(strlen(StartString)); + + std::vector<std::string>::iterator it = argv.begin(); + unsigned idx = 0; + while( it != argv.end() ) { + // (*) does start string match the given option? + // NO -> goto next option + if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; } + + // append the found tail to the result vector + result.push_back(__convert_to_type((*it).substr(N), Default)); + + // adapt the nominus vector + std::vector<unsigned>::iterator nit = idx_nominus.begin(); + for(; nit != idx_nominus.end(); ++nit) { + if( *nit == idx ) { + idx_nominus.erase(nit); + for(; nit != idx_nominus.end(); ++nit) *nit -= 1; + break; + } + } + + // erase the found option + argv.erase(it); + + // 100% safe solution: set iterator back to the beginning. + // (normally, 'it--' would be enough, but who knows how the + // iterator is implemented and .erase() definitely invalidates + // the current iterator position. + if( argv.empty() ) break; + it = argv.begin(); + } + cursor = 0; + nominus_cursor = -1; + return result; +} + + + + + +inline const char* +GetPot::__match_starting_string(const char* StartString) + // pointer to the place where the string after + // the match inside the found argument starts. + // 0 no argument matches the starting string. +{ + const unsigned N = static_cast<unsigned int>(strlen(StartString)); + unsigned OldCursor = cursor; + + if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1; + search_failed_f = true; + + // (*) first loop from cursor position until end + unsigned c = cursor; + for(; c < argv.size(); c++) { + if( strncmp(StartString, argv[c].c_str(), N) == 0) + { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); } + } + + if( ! search_loop_f ) return false; + + // (*) second loop from 0 to old cursor position + for(c = 1; c < OldCursor; c++) { + if( strncmp(StartString, argv[c].c_str(), N) == 0) + { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); } + } + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// (*) search for flags +//............................................................................. +// +inline bool +GetPot::options_contain(const char* FlagList) const +{ + // go through all arguments that start with a '-' (but not '--') + std::string str; + STRING_VECTOR::const_iterator it = argv.begin(); + for(; it != argv.end(); ++it) { + str = __get_remaining_string(*it, prefix); + + if( str.length() >= 2 && str[0] == '-' && str[1] != '-' ) + if( __check_flags(str, FlagList) ) return true; + } + return false; +} + +inline bool +GetPot::argument_contains(unsigned Idx, const char* FlagList) const +{ + if( Idx >= argv.size() ) return false; + + // (*) record requested of argument for later ufo-detection + // an argument that is checked for flags is considered to be 'requested' + ((GetPot*)this)->__record_argument_request(argv[Idx]); + + if( prefix == "" ) + // search argument for any flag in flag list + return __check_flags(argv[Idx], FlagList); + + // if a prefix is set, then the argument index is the index + // inside the 'namespace' + // => only check list of arguments that start with prefix + unsigned no_matches = 0; + unsigned i=0; + for(; i<argv.size(); ++i) { + const std::string Remain = __get_remaining_string(argv[i], prefix); + if( Remain != "") { + no_matches += 1; + if( no_matches == Idx) + return __check_flags(Remain, FlagList); + } + } + // no argument in this namespace + return false; +} + +inline bool +GetPot::__check_flags(const std::string& Str, const char* FlagList) const +{ + const char* p=FlagList; + for(; *p != '\0' ; p++) + if( Str.find(*p) != std::string::npos ) return true; // found something + return false; +} + +/////////////////////////////////////////////////////////////////////////////// +// (*) nominus arguments +inline STRING_VECTOR +GetPot::nominus_vector() const + // return vector of nominus arguments +{ + STRING_VECTOR nv; + std::vector<unsigned>::const_iterator it = idx_nominus.begin(); + for(; it != idx_nominus.end(); ++it) { + nv.push_back(argv[*it]); + + // (*) record for later ufo-detection + // when a nominus vector is requested, the entire set of nominus arguments are + // tagged as 'requested' + ((GetPot*)this)->__record_argument_request(argv[*it]); + } + return nv; +} + +inline std::string +GetPot::next_nominus() +{ + if( nominus_cursor < int(idx_nominus.size()) - 1 ) { + const std::string Tmp = argv[idx_nominus[++nominus_cursor]]; + + // (*) record for later ufo-detection + __record_argument_request(Tmp); + + // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer + // to something that does no longer exist. + return Tmp; + } + return std::string(""); +} + +/////////////////////////////////////////////////////////////////////////////// +// (*) variables +//............................................................................. +// +inline int +GetPot::operator()(const char* VarName, int Default) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + return __convert_to_type(sv->original, Default); +} + +inline double +GetPot::operator()(const char* VarName, const double& Default) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + return __convert_to_type(sv->original, Default); +} + +inline const std::string +GetPot::operator()(const char* VarName, const char* Default) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + // -- returning a c_str() pointer is OK here, since the variable remains existant, + // while 'sv' of course is delete at the end of the function. + return sv->original; +} + +inline int +GetPot::operator()(const char* VarName, int Default, unsigned Idx) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + const std::string* element = sv->get_element(Idx); + if( element == 0 ) return Default; + return __convert_to_type(*element, Default); +} + +inline double +GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + const std::string* element = sv->get_element(Idx); + if( element == 0 ) return Default; + return __convert_to_type(*element, Default); +} + +inline const std::string +GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const +{ + // (*) recording of requested variables happens in '__find_variable()' + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return Default; + const std::string* element = sv->get_element(Idx); + if( element == 0 ) return Default; + return *element; +} + +inline void +GetPot::__record_argument_request(const std::string& Name) +{ + if( ! __request_recording_f ) return; + + // (*) record requested variable for later ufo detection + _requested_arguments.push_back(Name); + + // (*) record considered section for ufo detection + STRING_VECTOR STree = __get_section_tree(Name); + victorate(std::string, STree, it) + if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() ) + if( section.length() != 0 ) _requested_sections.push_back(*it); +} + +inline void +GetPot::__record_variable_request(const std::string& Name) +{ + if( ! __request_recording_f ) return; + + // (*) record requested variable for later ufo detection + _requested_variables.push_back(Name); + + // (*) record considered section for ufo detection + STRING_VECTOR STree = __get_section_tree(Name); + victorate(std::string, STree, it) + if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() ) + if( section.length() != 0 ) _requested_sections.push_back(*it); +} + +// (*) following functions are to be used from 'outside', after getpot has parsed its +// arguments => append an argument in the argument vector that reflects the addition +inline void +GetPot::__set_variable(const char* VarName, const char* Value) +{ + const GetPot::variable* Var = __find_variable(VarName); + if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str())); + else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str()); +} + +inline void +GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */) +{ + const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value); + argv.push_back(Arg); + __set_variable(VarName, Value); + + // if user does not specify the variable as 'not being requested' it will be + // considered amongst the requested variables + if( Requested ) __record_variable_request(Arg); +} + +inline void +GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */) +{ __set_variable(VarName, __double2string(Value).c_str()); } + +inline void +GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */) +{ __set_variable(VarName, __int2string(Value).c_str()); } + + +inline unsigned +GetPot::vector_variable_size(const char* VarName) const +{ + const variable* sv = __find_variable(VarName); + if( sv == 0 ) return 0; + return static_cast<unsigned int>(sv->value.size()); +} + +inline STRING_VECTOR +GetPot::get_variable_names() const +{ + STRING_VECTOR result; + std::vector<GetPot::variable>::const_iterator it = variables.begin(); + for(; it != variables.end(); ++it) { + const std::string Tmp = __get_remaining_string((*it).name, prefix); + if( Tmp != "" ) result.push_back(Tmp); + } + return result; +} + +inline STRING_VECTOR +GetPot::get_section_names() const +{ return section_list; } + +inline const GetPot::variable* +GetPot::__find_variable(const char* VarName) const +{ + const std::string Name = prefix + VarName; + + // (*) record requested variable for later ufo detection + ((GetPot*)this)->__record_variable_request(Name); + + std::vector<variable>::const_iterator it = variables.begin(); + for(; it != variables.end(); ++it) { + if( (*it).name == Name ) return &(*it); + } + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// (*) ouput (basically for debugging reasons +//............................................................................. +// +inline int +GetPot::print() const +{ + std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl; + STRING_VECTOR::const_iterator it = argv.begin(); + for(; it != argv.end(); ++it) + std::cout << *it << std::endl; + std::cout << std::endl; + return 1; +} + +// (*) dollar bracket expressions (DBEs) ------------------------------------ +// +// 1) Entry Function: __DBE_expand_string() +// Takes a string such as +// +// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}" +// +// calls __DBE_expand() for each of the expressions +// +// ${+ ${x} ${y}} +// ${& ${section} ${subsection}} +// ${Title} +// +// and returns the string +// +// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene" +// +// assuming that +// x = "4699" +// y = "12" +// section = "1." +// subsection = "01" +// title = "Mit den Clowns kamen die Schwaene" +// +// 2) __DBE_expand(): +// +// checks for the command, i.e. the 'sign' that follows '${' +// divides the argument list into sub-expressions using +// __DBE_get_expr_list() +// +// ${+ ${x} ${y}} -> "${x}" "${y}" +// ${& ${section} ${subsection}} -> "${section}" "${subsection}" +// ${Title} -> Nothing, variable expansion +// +// 3) __DBE_expression_list(): +// +// builds a vector of unbracketed whitespace separated strings, i.e. +// +// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}" +// +// is split into a vector +// +// [0] ${Number}.a +// [1] ${: Das Marmorbild} +// [2] AB-${& Author= ${Eichendorf}}-1870 +// +// Each sub-expression is expanded using expand(). +//--------------------------------------------------------------------------- +inline std::string +GetPot::__DBE_expand_string(const std::string str) +{ + // Parses for closing operators '${ }' and expands them letting + // white spaces and other letters as they are. + std::string new_string = ""; + unsigned open_brackets = 0; + unsigned first = 0; + unsigned i = 0; + for(; i<str.size(); ++i) { + if( i < str.size() - 2 && str.substr(i, 2) == "${" ) { + if( open_brackets == 0 ) first = i+2; + open_brackets++; + } + else if( str[i] == '}' && open_brackets > 0) { + open_brackets -= 1; + if( open_brackets == 0 ) { + const std::string Replacement = __DBE_expand(str.substr(first, i - first)); + new_string += Replacement; + } + } + else if( open_brackets == 0 ) + new_string += str[i]; + } + return new_string; +} + +inline STRING_VECTOR +GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber) + // ensures that the resulting vector has the expected number + // of arguments, but they may contain an error message +{ + std::string str = str_; + // Separates expressions by non-bracketed whitespaces, expands them + // and puts them into a list. + + unsigned i=0; + // (1) eat initial whitespaces + for(; i < str.size(); ++i) + if( ! isspace(str[i]) ) break; + + STRING_VECTOR expr_list; + unsigned open_brackets = 0; + std::vector<unsigned> start_idx; + unsigned start_new_string = i; + unsigned l = static_cast<unsigned int>(str.size()); + + // (2) search for ${ } expressions ... + while( i < l ) { + const char letter = str[i]; + // whitespace -> end of expression + if( isspace(letter) && open_brackets == 0) { + expr_list.push_back(str.substr(start_new_string, i - start_new_string)); + bool no_breakout_f = true; + for(++i; i < l ; ++i) { + if( ! isspace(str[i]) ) + { no_breakout_f = false; start_new_string = i; break; } + } + if( no_breakout_f ) { + // end of expression list + if( expr_list.size() < ExpectedNumber ) { + const std::string pre_tmp("<< ${ }: missing arguments>>"); + STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp); + expr_list.insert(expr_list.end(), tmp.begin(), tmp.end()); + } + return expr_list; + } + } + + // dollar-bracket expression + if( str.length() >= i+2 && str.substr(i, 2) == "${" ) { + open_brackets++; + start_idx.push_back(i+2); + } + else if( letter == '}' && open_brackets > 0) { + int start = start_idx[start_idx.size()-1]; + start_idx.pop_back(); + const std::string Replacement = __DBE_expand(str.substr(start, i-start)); + if( start - 3 < (int)0) + str = Replacement + str.substr(i+1); + else + str = str.substr(0, start-2) + Replacement + str.substr(i+1); + l = static_cast<unsigned int>(str.size()); + i = start + static_cast<unsigned int>(Replacement.size()) - 3; + open_brackets--; + } + ++i; + } + + // end of expression list + expr_list.push_back(str.substr(start_new_string, i-start_new_string)); + + if( expr_list.size() < ExpectedNumber ) { + const std::string pre_tmp("<< ${ }: missing arguments>>"); + STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp); + expr_list.insert(expr_list.end(), tmp.begin(), tmp.end()); + } + + return expr_list; +} + +inline const GetPot::variable* +GetPot::__DBE_get_variable(std::string VarName) +{ + static GetPot::variable ev; + std::string secure_Prefix = prefix; + + prefix = section; + // (1) first search in currently active section + const GetPot::variable* var = __find_variable(VarName.c_str()); + if( var != 0 ) { prefix = secure_Prefix; return var; } + + // (2) search in root name space + prefix = ""; + var = __find_variable(VarName.c_str()); + if( var != 0 ) { prefix = secure_Prefix; return var; } + + prefix = secure_Prefix; + + // error occured => variable name == "" + char* tmp = new char[VarName.length() + 25]; +#ifndef WIN32 + snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25), +#else + _snprintf(tmp, sizeof(char)*(VarName.length() + 25), +#endif + "<<${ } variable '%s' undefined>>", VarName.c_str()); + ev.name = ""; + ev.original = std::string(tmp); + delete [] tmp; + return &ev; +} + +inline std::string +GetPot::__DBE_expand(const std::string expr) +{ + // ${: } pure text + if( expr[0] == ':' ) + return expr.substr(1); + + // ${& expr expr ... } text concatination + else if( expr[0] == '&' ) { + const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1); + + STRING_VECTOR::const_iterator it = A.begin(); + std::string result = *it++; + for(; it != A.end(); ++it) result += *it; + + return result; + } + + // ${<-> expr expr expr} text replacement + else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3); + std::string::size_type tmp = 0; + const std::string::size_type L = A[1].length(); + while( (tmp = A[0].find(A[1])) != std::string::npos ) { + A[0].replace(tmp, L, A[2]); + } + return A[0]; + } + // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions + else if( expr[0] == '+' ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + STRING_VECTOR::const_iterator it = A.begin(); + double result = __convert_to_type(*it++, 0.0); + for(; it != A.end(); ++it) + result += __convert_to_type(*it, 0.0); + + return __double2string(result); + } + else if( expr[0] == '-' ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + STRING_VECTOR::const_iterator it = A.begin(); + double result = __convert_to_type(*it++, 0.0); + for(; it != A.end(); ++it) + result -= __convert_to_type(*it, 0.0); + + return __double2string(result); + } + else if( expr[0] == '*' ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + STRING_VECTOR::const_iterator it = A.begin(); + double result = __convert_to_type(*it++, 0.0); + for(; it != A.end(); ++it) + result *= __convert_to_type(*it, 0.0); + + return __double2string(result); + } + else if( expr[0] == '/' ) { + + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + STRING_VECTOR::const_iterator it = A.begin(); + double result = __convert_to_type(*it++, 0.0); + if( result == 0 ) return "0.0"; + for(; it != A.end(); ++it) { + const double Q = __convert_to_type(*it, 0.0); + if( Q == 0.0 ) return "0.0"; + result /= Q; + } + return __double2string(result); + } + + // ${^ ... } power expressions + else if( expr[0] == '^' ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + STRING_VECTOR::const_iterator it = A.begin(); + double result = __convert_to_type(*it++, 0.0); + for(; it != A.end(); ++it) + result = pow(result, __convert_to_type(*it, 0.0)); + return __double2string(result); + } + + // ${== } ${<= } ${>= } comparisons (return the number of the first 'match' + else if( expr.length() >= 2 && + ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" || + expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) { + // differentiate between two and one sign operators + unsigned op = 0; + enum { EQ, GEQ, LEQ, GT, LT }; + if ( expr.substr(0, 2) == "==" ) op = EQ; + else if ( expr.substr(0, 2) == ">=" ) op = GEQ; + else if ( expr.substr(0, 2) == "<=" ) op = LEQ; + else if ( expr[0] == '>' ) op = GT; + else /* "<" */ op = LT; + + STRING_VECTOR a; + if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2); + else a = __DBE_get_expr_list(expr.substr(2), 2); + + std::string x_orig = a[0]; + double x = __convert_to_type(x_orig, 1e37); + unsigned i = 1; + + STRING_VECTOR::const_iterator y_orig = a.begin(); + for(y_orig++; y_orig != a.end(); y_orig++) { + double y = __convert_to_type(*y_orig, 1e37); + + // set the strings as reference if one wasn't a number + if ( x == 1e37 || y == 1e37 ) { + // it's a string comparison + if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) || + (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) || + (op == LT && x_orig < *y_orig) ) + return __int2string(i); + } + else { + // it's a number comparison + if( (op == EQ && x == y) || (op == GEQ && x >= y) || + (op == LEQ && x <= y) || (op == GT && x > y) || + (op == LT && x < y) ) + return __int2string(i); + } + ++i; + } + + // nothing fulfills the condition => return 0 + return "0"; + } + // ${?? expr expr} select + else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) { + STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2); + double x = __convert_to_type(a[0], 1e37); + // last element is always the default argument + if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1]; + + // round x to closest integer + return a[int(x+0.5)]; + } + // ${? expr expr expr} if then else conditions + else if( expr[0] == '?' ) { + STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2); + if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1]; + else if( a.size() > 2 ) return a[2]; + } + // ${! expr} maxro expansion + else if( expr[0] == '!' ) { + const GetPot::variable* Var = __DBE_get_variable(expr.substr(1)); + // error + if( Var->name == "" ) return std::string(Var->original); + + const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2); + return A[0]; + } + // ${@: } - string subscription + else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) { + const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2); + double x = __convert_to_type(A[1], 1e37); + + // last element is always the default argument + if( x == 1e37 || x < 0 || x >= A[0].size() - 1) + return "<<1st index out of range>>"; + + if( A.size() > 2 ) { + double y = __convert_to_type(A[2], 1e37); + if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x ) + return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5)); + else if( y == -1 ) + return A[0].substr(int(x+0.5)); + return "<<2nd index out of range>>"; + } + else { + char* tmp = new char[2]; + tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0'; + std::string result(tmp); + delete [] tmp; + return result; + } + } + // ${@ } - vector subscription + else if( expr[0] == '@' ) { + STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2); + const GetPot::variable* Var = __DBE_get_variable(A[0]); + // error + if( Var->name == "" ) { + // make a copy of the string if an error occured + // (since the error variable is a static variable inside get_variable()) + return std::string(Var->original); + } + + double x = __convert_to_type(A[1], 1e37); + + // last element is always the default argument + if (x == 1e37 || x < 0 || x >= Var->value.size() ) + return "<<1st index out of range>>"; + + if ( A.size() > 2) { + double y = __convert_to_type(A[2], 1e37); + int begin = int(x+0.5); + int end = 0; + if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x) + end = int(y+1.5); + else if( y == -1 ) + end = static_cast<unsigned int>(Var->value.size()); + else + return "<<2nd index out of range>>"; + + std::string result = *(Var->get_element(begin)); + int i = begin+1; + for(; i < end; ++i) + result += std::string(" ") + *(Var->get_element(i)); + return result; + } + else + return *(Var->get_element(int(x+0.5))); + } + + const STRING_VECTOR A = __DBE_get_expr_list(expr, 1); + const GetPot::variable* B = __DBE_get_variable(A[0]); + + // make a copy of the string if an error occured + // (since the error variable is a static variable inside get_variable()) + if( B->name == "" ) return std::string(B->original); + // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces + // with: else return B->original (thanks)) + return B->original; +} + + +/////////////////////////////////////////////////////////////////////////////// +// (*) unidentified flying objects +//............................................................................. +// +inline bool +GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const +{ + victorate(std::string, VecStr, itk) { + if( *itk == Str ) return true; + } + return false; +} + +inline STRING_VECTOR +GetPot::unidentified_arguments(unsigned Number, + const char* KnownArgument1, ...) const +{ + STRING_VECTOR known_arguments; + + // (1) create a vector of known arguments + if( Number == 0 ) return STRING_VECTOR(); + + va_list ap; + va_start(ap, KnownArgument1); + known_arguments.push_back(std::string(KnownArgument1)); + unsigned i=1; + for(; i<Number; ++i) + known_arguments.push_back(std::string(va_arg(ap, char *))); + va_end(ap); + + return unidentified_arguments(known_arguments); +} + +inline STRING_VECTOR +GetPot::unidentified_arguments() const +{ return unidentified_arguments(_requested_arguments); } + +inline STRING_VECTOR +GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const +{ + STRING_VECTOR ufos; + STRING_VECTOR::const_iterator it = argv.begin(); + ++it; // forget about argv[0] (application or filename) + for(; it != argv.end(); ++it) { + // -- argument belongs to prefixed section ? + const std::string arg = __get_remaining_string(*it, prefix); + if( arg == "" ) continue; + + // -- check if in list + if( __search_string_vector(Knowns, arg) == false) + ufos.push_back(*it); + } + return ufos; +} + +inline STRING_VECTOR +GetPot::unidentified_options(unsigned Number, + const char* KnownOption1, ...) const +{ + STRING_VECTOR known_options; + + // (1) create a vector of known arguments + if( Number == 0 ) return STRING_VECTOR(); + + va_list ap; + va_start(ap, KnownOption1); + known_options.push_back(std::string(KnownOption1)); + unsigned i=1; + for(; i<Number; ++i) + known_options.push_back(std::string(va_arg(ap, char *))); + va_end(ap); + + return unidentified_options(known_options); +} + +inline STRING_VECTOR +GetPot::unidentified_options() const +{ + // -- every option is an argument. + // -- the set of requested arguments contains the set of requested options. + // -- IF the set of requested arguments contains unrequested options, + // THEN they were requested as 'follow' and 'next' arguments and not as real options. + // + // => it is not necessary to separate requested options from the list + STRING_VECTOR option_list; + victorate(std::string, _requested_arguments, it) { + const std::string arg = *it; + if( arg.length() == 0 ) continue; + if( arg[0] == '-' ) option_list.push_back(arg); + } + return unidentified_options(option_list); +} + +inline STRING_VECTOR +GetPot::unidentified_options(const STRING_VECTOR& Knowns) const +{ + STRING_VECTOR ufos; + STRING_VECTOR::const_iterator it = argv.begin(); + ++it; // forget about argv[0] (application or filename) + for(; it != argv.end(); ++it) { + // -- argument belongs to prefixed section ? + const std::string arg = __get_remaining_string(*it, prefix); + if( arg == "" ) continue; + + // is argument really an option (starting with '-') ? + if( arg.length() < 1 || arg[0] != '-' ) continue; + + if( __search_string_vector(Knowns, arg) == false) + ufos.push_back(*it); + } + + return ufos; +} + +inline std::string +GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const + // Two modes: + // ArgumentNumber >= 0 check specific argument + // ArgumentNumber == -1 check all options starting with one '-' + // for flags +{ + std::string ufos; + STRING_VECTOR known_arguments; + std::string KFL(KnownFlagList); + + // (2) iteration over '-' arguments (options) + if( ArgumentNumber == -1 ) { + STRING_VECTOR::const_iterator it = argv.begin(); + ++it; // forget about argv[0] (application or filename) + for(; it != argv.end(); ++it) { + // -- argument belongs to prefixed section ? + const std::string arg = __get_remaining_string(*it, prefix); + if( arg == "" ) continue; + + // -- does arguments start with '-' (but not '--') + if ( arg.length() < 2 ) continue; + else if( arg[0] != '-' ) continue; + else if( arg[1] == '-' ) continue; + + // -- check out if flags inside option are contained in KnownFlagList + const char* p=arg.c_str(); + p++; // skip starting minus + for(; *p != '\0' ; p++) + if( KFL.find(*p) == std::string::npos ) ufos += *p; + } + } + // (1) check specific argument + else { + // -- only check arguments that start with prefix + int no_matches = 0; + unsigned i=1; + for(; i<argv.size(); ++i) { + const std::string Remain = __get_remaining_string(argv[i], prefix); + if( Remain != "") { + no_matches++; + if( no_matches == ArgumentNumber) { + // -- the right argument number inside the section is found + // => check it for flags + const char* p = Remain.c_str(); + p++; // skip starting minus + for(; *p != '\0' ; p++) + if( KFL.find(*p) == std::string::npos ) ufos += *p; + return ufos; + } + } + } + } + return ufos; +} + +inline STRING_VECTOR +GetPot::unidentified_variables(unsigned Number, + const char* KnownVariable1, ...) const +{ + STRING_VECTOR known_variables; + + // create vector of known arguments + if( Number == 0 ) return STRING_VECTOR(); + + va_list ap; + va_start(ap, KnownVariable1); + known_variables.push_back(std::string(KnownVariable1)); + unsigned i=1; + for(; i<Number; ++i) + known_variables.push_back(std::string(va_arg(ap, char *))); + va_end(ap); + + return unidentified_variables(known_variables); +} + +inline STRING_VECTOR +GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const +{ + STRING_VECTOR ufos; + + victorate(GetPot::variable, variables, it) { + // -- check if variable has specific prefix + const std::string var_name = __get_remaining_string((*it).name, prefix); + if( var_name == "" ) continue; + + // -- check if variable is known + if( __search_string_vector(Knowns, var_name) == false) + ufos.push_back((*it).name); + } + return ufos; +} + +inline STRING_VECTOR +GetPot::unidentified_variables() const +{ return unidentified_variables(_requested_variables); } + + +inline STRING_VECTOR +GetPot::unidentified_sections(unsigned Number, + const char* KnownSection1, ...) const +{ + STRING_VECTOR known_sections; + + // (1) create a vector of known arguments + if( Number == 0 ) return STRING_VECTOR(); + + va_list ap; + va_start(ap, KnownSection1); + known_sections.push_back(std::string(KnownSection1)); + unsigned i=1; + for(; i<Number; ++i) { + std::string tmp = std::string(va_arg(ap, char *)); + if( tmp.length() == 0 ) continue; + if( tmp[tmp.length()-1] != '/' ) tmp += '/'; + known_sections.push_back(tmp); + } + va_end(ap); + + return unidentified_sections(known_sections); +} + +inline STRING_VECTOR +GetPot::unidentified_sections() const +{ return unidentified_sections(_requested_sections); } + +inline STRING_VECTOR +GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const +{ + STRING_VECTOR ufos; + + victorate(std::string, section_list, it) { + // -- check if section conform to prefix + const std::string sec_name = __get_remaining_string(*it, prefix); + if( sec_name == "" ) continue; + + // -- check if section is known + if( __search_string_vector(Knowns, sec_name) == false ) + ufos.push_back(*it); + } + + return ufos; +} + + +inline STRING_VECTOR +GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const +{ + STRING_VECTOR known_nominuses; + + // create vector of known arguments + if( Number == 0 ) return STRING_VECTOR(); + + va_list ap; + va_start(ap, Known); + known_nominuses.push_back(std::string(Known)); + unsigned i=1; + for(; i<Number; ++i) { + std::string tmp = std::string(va_arg(ap, char *)); + if( tmp.length() == 0 ) continue; + known_nominuses.push_back(tmp); + } + va_end(ap); + + return unidentified_nominuses(known_nominuses); +} + +inline STRING_VECTOR +GetPot::unidentified_nominuses() const { + // -- every nominus is an argument. + // -- the set of requested arguments contains the set of requested nominuss. + // -- IF the set of requested arguments contains unrequested nominuss, + // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses. + // + // => it is not necessary to separate requested nominus from the list + + return unidentified_nominuses(_requested_arguments); +} + +inline STRING_VECTOR +GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const +{ + STRING_VECTOR ufos; + + // (2) iterate over all arguments + STRING_VECTOR::const_iterator it = argv.begin(); + ++it; // forget about argv[0] (application or filename) + for(; it != argv.end(); ++it) { + // -- check if nominus part of prefix + const std::string arg = __get_remaining_string(*it, prefix); + if( arg == "" ) continue; + + if( arg.length() < 1 ) continue; + // option ? --> not a nomius + if( arg[0] == '-' ) continue; + // section ? --> not a real nominus + if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue; + // variable definition ? --> not a real nominus + bool continue_f = false; + unsigned i=0; + for(; i<arg.length() ; ++i) + if( arg[i] == '=' ) { continue_f = true; break; } + if( continue_f ) continue; + + // real nominuses are compared with the given list + if( __search_string_vector(Knowns, arg) == false ) + ufos.push_back(*it); + } + return ufos; +} + + +/////////////////////////////////////////////////////////////////////////////// +// (*) variable class +//............................................................................. +// +inline +GetPot::variable::variable() +{} + +inline +GetPot::variable::variable(const variable& That) +{ +#ifdef WIN32 + operator=(That); +#else + GetPot::variable::operator=(That); +#endif +} + + +inline +GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator) + : name(Name) +{ + // make a copy of the 'Value' + take(Value, FieldSeparator); +} + +inline const std::string* +GetPot::variable::get_element(unsigned Idx) const +{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); } + +inline void +GetPot::variable::take(const char* Value, const char* FieldSeparator) +{ + original = std::string(Value); + + // separate string by white space delimiters using 'strtok' + // thread safe usage of strtok (no static members) + char* spt = 0; + // make a copy of the 'Value' + char* copy = new char[strlen(Value)+1]; + strcpy(copy, Value); + char* follow_token = strtok_r(copy, FieldSeparator, &spt); + if( value.size() != 0 ) value.erase(value.begin(), value.end()); + while(follow_token != 0) { + value.push_back(std::string(follow_token)); + follow_token = strtok_r(NULL, FieldSeparator, &spt); + } + + delete [] copy; +} + +inline +GetPot::variable::~variable() +{} + +inline GetPot::variable& +GetPot::variable::operator=(const GetPot::variable& That) +{ + if( &That != this) { + name = That.name; + value = That.value; + original = That.original; + } + return *this; +} + +#undef victorate + + +#endif // __include_guard_GETPOT_H__ + + + diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt new file mode 100755 index 0000000000..b1e3f5a263 --- /dev/null +++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/LPGL.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README new file mode 100755 index 0000000000..3d55352a6b --- /dev/null +++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/README @@ -0,0 +1,50 @@ +GetPot - C++: +-------------- + +Attention: This version contains a couple of beautiful +---------- new features, that are not documented yet. + + E.g.: -- automated ufo detection + -- arbitrary comment delimiters + -- arbitrary vector field separators + -- tails, i.e. easy access to all tails + of options such as '-L' or '-I'. + + Please, refere to the example/ directory + for usage descriptions. + +This is the C++ version of the popular GetPot library for +command line and input file parsing. The documentation +can be downloaded at: + + http://getpot.sourceforge.net + +The files in the 'examples' directory should be enough, though, to be +able to use this library. It is fairly easy to use. + +Installation: +------------- + +In order to install GetPot, simply copy the file 'GetPot' +somewhere where your c++ compiler can find it. + +The 'file emacs-getpot-mode.el' contains some lines of +emacs-lisp code. If you append these lines to your .emacs +file, it will highlight your 'getpot' - input files. + +Bug reports, Feature requests: +------------------------------ + +Please, notify me in case there are any bugs or you think +that there should be more features in the library. +My email address is: + +fschaef@users.sourceforge.net + +Thanks for using this software. +Enjoy ! + + +Juli 2005, +Frank R. Schaefer + diff --git a/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp new file mode 100755 index 0000000000..fe820c91a2 --- /dev/null +++ b/utils/zenutils/libraries/getpot-c++-1.1.17/getpot/getpot.hpp @@ -0,0 +1,2435 @@ +// -*- c++ -*-
+// GetPot Version $$Version$$ $$Date$$
+//
+// WEBSITE: http://getpot.sourceforge.net
+//
+// NOTE: The LPGL License for this library is only valid in case that
+// it is not used for the production or development of applications
+// dedicated to military industry. This is what the author calls
+// the 'unofficial peace version of the LPGL'.
+//
+// This library is free software; you can redistribute it and/or modify
+// it under the terms of the GNU Lesser General Public License as
+// published by the Free Software Foundation; either version 2.1 of the
+// License, or (at your option) any later version.
+//
+// This library 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
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
+// USA
+//
+// (C) 2001-2005 Frank R. Schaefer <fschaef@users.sf.net>
+//==========================================================================
+
+#ifndef __include_guard_GETPOT_H__
+#define __include_guard_GETPOT_H__
+
+#if defined(WIN32) || defined(SOLARIS_RAW) || (__GNUC__ == 2) || defined(__HP_aCC)
+#define strtok_r(a, b, c) strtok(a, b)
+#endif // WINDOWS or SOLARIS or gcc 2.* or HP aCC
+
+extern "C" {
+// leave the 'extern C' to make it 100% sure to work -
+// expecially with older distributions of header files.
+#ifndef WIN32
+// this is necessary (depending on OS)
+#include <ctype.h>
+#endif
+#include <stdio.h>
+#include <stdarg.h>
+#include <assert.h>
+}
+#include <cmath>
+#include <string>
+#include <vector>
+#include <algorithm>
+
+#include <fstream>
+#include <iostream> // not every compiler distribution includes <iostream>
+// // with <fstream>
+
+typedef std::vector<std::string> STRING_VECTOR;
+
+#define victorate(TYPE, VARIABLE, ITERATOR) \
+ std::vector<TYPE>::const_iterator ITERATOR = (VARIABLE).begin(); \
+ for(; (ITERATOR) != (VARIABLE).end(); (ITERATOR)++)
+
+
+class GetPot {
+ //--------
+ inline void __basic_initialization();
+public:
+ // (*) constructors, destructor, assignment operator -----------------------
+ inline GetPot();
+ inline GetPot(const GetPot&);
+ inline GetPot(const int argc_, char** argv_,
+ const char* FieldSeparator=0x0);
+ inline GetPot(const char* FileName,
+ const char* CommentStart=0x0, const char* CommentEnd=0x0,
+ const char* FieldSeparator=0x0);
+ inline ~GetPot();
+ inline GetPot& operator=(const GetPot&);
+
+
+ // (*) absorbing contents of another GetPot object
+ inline void absorb(const GetPot& That);
+ // -- for ufo detection: recording requested arguments, options etc.
+ inline void clear_requests();
+ inline void disable_request_recording() { __request_recording_f = false; }
+ inline void enable_request_recording() { __request_recording_f = true; }
+
+ // (*) direct access to command line arguments -----------------------------
+ inline const std::string operator[](unsigned Idx) const;
+ inline int get(unsigned Idx, int Default) const;
+ inline double get(unsigned Idx, const double& Default) const;
+ inline const std::string get(unsigned Idx, const char* Default) const;
+ inline unsigned size() const;
+
+ // (*) flags ---------------------------------------------------------------
+ inline bool options_contain(const char* FlagList) const;
+ inline bool argument_contains(unsigned Idx, const char* FlagList) const;
+
+ // (*) variables -----------------------------------------------------------
+ // -- scalar values
+ inline int operator()(const char* VarName, int Default) const;
+ inline double operator()(const char* VarName, const double& Default) const;
+ inline const std::string operator()(const char* VarName, const char* Default) const;
+ // -- vectors
+ inline int operator()(const char* VarName, int Default, unsigned Idx) const;
+ inline double operator()(const char* VarName, const double& Default, unsigned Idx) const;
+ inline const std::string operator()(const char* VarName, const char* Default, unsigned Idx) const;
+
+ // -- setting variables
+ // i) from outside of GetPot (considering prefix etc.)
+ // ii) from inside, use '__set_variable()' below
+ inline void set(const char* VarName, const char* Value, const bool Requested = true);
+ inline void set(const char* VarName, const double& Value, const bool Requested = true);
+ inline void set(const char* VarName, const int Value, const bool Requested = true);
+
+ inline unsigned vector_variable_size(const char* VarName) const;
+ inline STRING_VECTOR get_variable_names() const;
+ inline STRING_VECTOR get_section_names() const;
+
+
+ // (*) cursor oriented functions -------------------------------------------
+ inline void set_prefix(const char* Prefix) { prefix = std::string(Prefix); }
+ inline bool search_failed() const { return search_failed_f; }
+
+ // -- enable/disable search for an option in loop
+ inline void disable_loop() { search_loop_f = false; }
+ inline void enable_loop() { search_loop_f = true; }
+
+ // -- reset cursor to position '1'
+ inline void reset_cursor();
+ inline void init_multiple_occurrence();
+
+ // -- search for a certain option and set cursor to position
+ inline bool search(const char* option);
+ inline bool search(unsigned No, const char* P, ...);
+ // -- get argument at cursor++
+ inline int next(int Default);
+ inline double next(const double& Default);
+ inline const std::string next(const char* Default);
+ // -- search for option and get argument at cursor++
+ inline int follow(int Default, const char* Option);
+ inline double follow(const double& Default, const char* Option);
+ inline const std::string follow(const char* Default, const char* Option);
+ // -- search for one of the given options and get argument that follows it
+ inline int follow(int Default, unsigned No, const char* Option, ...);
+ inline double follow(const double& Default, unsigned No, const char* Option, ...);
+ inline const std::string follow(const char* Default, unsigned No, const char* Option, ...);
+ // -- lists of nominuses following an option
+ inline std::vector<std::string> nominus_followers(const char* Option);
+ inline std::vector<std::string> nominus_followers(unsigned No, ...);
+
+ // -- directly followed arguments
+ inline int direct_follow(int Default, const char* Option);
+ inline double direct_follow(const double& Default, const char* Option);
+ inline const std::string direct_follow(const char* Default, const char* Option);
+
+ inline std::vector<std::string> string_tails(const char* StartString);
+ inline std::vector<int> int_tails(const char* StartString, const int Default = 1);
+ inline std::vector<double> double_tails(const char* StartString, const double Default = 1.0);
+
+ // (*) nominus arguments ---------------------------------------------------
+ inline STRING_VECTOR nominus_vector() const;
+ inline unsigned nominus_size() const { return static_cast<unsigned int>(idx_nominus.size()); }
+ inline std::string next_nominus();
+
+ // (*) unidentified flying objects -----------------------------------------
+ inline STRING_VECTOR unidentified_arguments(unsigned Number, const char* Known, ...) const;
+ inline STRING_VECTOR unidentified_arguments(const STRING_VECTOR& Knowns) const;
+ inline STRING_VECTOR unidentified_arguments() const;
+
+ inline STRING_VECTOR unidentified_options(unsigned Number, const char* Known, ...) const;
+ inline STRING_VECTOR unidentified_options(const STRING_VECTOR& Knowns) const;
+ inline STRING_VECTOR unidentified_options() const;
+
+ inline std::string unidentified_flags(const char* Known,
+ int ArgumentNumber /* =-1 */) const;
+
+ inline STRING_VECTOR unidentified_variables(unsigned Number, const char* Known, ...) const;
+ inline STRING_VECTOR unidentified_variables(const STRING_VECTOR& Knowns) const;
+ inline STRING_VECTOR unidentified_variables() const;
+
+ inline STRING_VECTOR unidentified_sections(unsigned Number, const char* Known, ...) const;
+ inline STRING_VECTOR unidentified_sections(const STRING_VECTOR& Knowns) const;
+ inline STRING_VECTOR unidentified_sections() const;
+
+ inline STRING_VECTOR unidentified_nominuses(unsigned Number, const char* Known, ...) const;
+ inline STRING_VECTOR unidentified_nominuses(const STRING_VECTOR& Knowns) const;
+ inline STRING_VECTOR unidentified_nominuses() const;
+
+ // (*) output --------------------------------------------------------------
+ inline int print() const;
+
+private:
+ // (*) Type Declaration ----------------------------------------------------
+ struct variable {
+ //-----------
+ // Variable to be specified on the command line or in input files.
+ // (i.e. of the form var='12 312 341')
+
+ // -- constructors, destructors, assignment operator
+ variable();
+ variable(const variable&);
+ variable(const char* Name, const char* Value, const char* FieldSeparator);
+ ~variable();
+ variable& operator=(const variable& That);
+
+ void take(const char* Value, const char* FieldSeparator);
+
+ // -- get a specific element in the string vector
+ // (return 0 if not present)
+ const std::string* get_element(unsigned Idx) const;
+
+ // -- data memebers
+ std::string name; // identifier of variable
+ STRING_VECTOR value; // value of variable stored in vector
+ std::string original; // value of variable as given on command line
+ };
+
+ // (*) member variables --------------------------------------------------------------
+ std::string prefix; // prefix automatically added in queries
+ std::string section; // (for dollar bracket parsing)
+ STRING_VECTOR section_list; // list of all parsed sections
+ // -- argument vector
+ STRING_VECTOR argv; // vector of command line arguments stored as strings
+ unsigned cursor; // cursor for argv
+ bool search_loop_f; // shall search start at beginning after
+ // // reaching end of arg array ?
+ bool search_failed_f; // flag indicating a failed search() operation
+ // // (e.g. next() functions react with 'missed')
+
+ // -- nominus vector
+ int nominus_cursor; // cursor for nominus_pointers
+ std::vector<unsigned> idx_nominus; // indecies of 'no minus' arguments
+
+ // -- variables
+ // (arguments of the form "variable=value")
+ std::vector<variable> variables;
+
+ // -- comment delimiters
+ std::string _comment_start;
+ std::string _comment_end;
+
+ // -- field separator (separating elements of a vector)
+ std::string _field_separator;
+
+ // -- some functions return a char pointer to a temporarily existing string
+ // this container makes them 'available' until the getpot object is destroyed.
+ std::vector<char*> __internal_string_container;
+
+ // -- keeping track about arguments that are requested, so that the UFO detection
+ // can be simplified
+ STRING_VECTOR _requested_arguments;
+ STRING_VECTOR _requested_variables;
+ STRING_VECTOR _requested_sections;
+
+ bool __request_recording_f; // speed: request recording can be turned off
+
+ // -- if an argument is requested record it and the 'tag' the section branch to which
+ // it belongs. Caution: both functions mark the sections as 'tagged'.
+ void __record_argument_request(const std::string& Arg);
+ void __record_variable_request(const std::string& Arg);
+
+ // (*) helper functions ----------------------------------------------------
+ // set variable from inside GetPot (no prefix considered)
+ inline void __set_variable(const char* VarName, const char* Value);
+
+ // -- produce three basic data vectors:
+ // - argument vector
+ // - nominus vector
+ // - variable dictionary
+ inline void __parse_argument_vector(const STRING_VECTOR& ARGV);
+
+ // -- helpers for argument list processing
+ // * search for a variable in 'variables' array
+ inline const variable* __find_variable(const char*) const;
+ // * support finding directly followed arguments
+ inline const char* __match_starting_string(const char* StartString);
+ // * support search for flags in a specific argument
+ inline bool __check_flags(const std::string& Str, const char* FlagList) const;
+ // * type conversion if possible
+ inline int __convert_to_type(const std::string& String, int Default) const;
+ inline double __convert_to_type(const std::string& String, double Default) const;
+ // * prefix extraction
+ const std::string __get_remaining_string(const std::string& String,
+ const std::string& Start) const;
+ // * search for a specific string
+ inline bool __search_string_vector(const STRING_VECTOR& Vec,
+ const std::string& Str) const;
+
+ // -- helpers to parse input file
+ // create an argument vector based on data found in an input file, i.e.:
+ // 1) delete comments (in between '_comment_start' '_comment_end')
+ // 2) contract assignment expressions, such as
+ // my-variable = '007 J. B.'
+ // into
+ // my-variable='007 J. B.'
+ // 3) interprete sections like '[../my-section]' etc.
+ inline void __skip_whitespace(std::istream& istr);
+ inline const std::string __get_next_token(std::istream& istr);
+ inline const std::string __get_string(std::istream& istr);
+ inline const std::string __get_until_closing_bracket(std::istream& istr);
+
+ inline STRING_VECTOR __read_in_stream(std::istream& istr);
+ inline STRING_VECTOR __read_in_file(const char* FileName);
+ inline std::string __process_section_label(const std::string& Section,
+ STRING_VECTOR& section_stack);
+
+ // -- dollar bracket expressions
+ std::string __DBE_expand_string(const std::string str);
+ std::string __DBE_expand(const std::string str);
+ const GetPot::variable* __DBE_get_variable(const std::string str);
+ STRING_VECTOR __DBE_get_expr_list(const std::string str, const unsigned ExpectedNumber);
+
+ std::string __double2string(const double& Value) const {
+ // -- converts a double integer into a string
+ char* tmp = new char[128];
+#ifndef WIN32
+ snprintf(tmp, (int)sizeof(char)*128, "%e", Value);
+#else
+ _snprintf(tmp, sizeof(char)*128, "%e", Value);
+#endif
+ std::string result(tmp);
+ delete [] tmp;
+ return result;
+ }
+
+ std::string __int2string(const int& Value) const {
+ // -- converts an integer into a string
+ char* tmp = new char[128];
+#ifndef WIN32
+ snprintf(tmp, (int)sizeof(char)*128, "%i", Value);
+#else
+ _snprintf(tmp, sizeof(char)*128, "%i", Value);
+#endif
+ std::string result(tmp);
+ delete [] tmp;
+ return result;
+ }
+
+ STRING_VECTOR __get_section_tree(const std::string& FullPath) {
+ // -- cuts a variable name into a tree of sub-sections. this is requested for recording
+ // requested sections when dealing with 'ufo' detection.
+ STRING_VECTOR result;
+ const char* Start = FullPath.c_str();
+
+ for(char *p = (char*)Start; *p ; p++) {
+ if( *p == '/' ) {
+ *p = '\0'; // set terminating zero for convinience
+ const std::string Section = Start;
+ *p = '/'; // reset slash at place
+ result.push_back(Section);
+ }
+ }
+
+ return result;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) constructors, destructor, assignment operator
+//.............................................................................
+//
+inline void
+GetPot::__basic_initialization()
+{
+ cursor = 0; nominus_cursor = -1;
+ search_failed_f = true; search_loop_f = true;
+ prefix = ""; section = "";
+
+ // automatic request recording for later ufo detection
+ __request_recording_f = true;
+
+ // comment start and end strings
+ _comment_start = std::string("#");
+ _comment_end = std::string("\n");
+
+ // default: separate vector elements by whitespaces
+ _field_separator = " \t\n";
+}
+
+inline
+GetPot::GetPot()
+{
+ __basic_initialization();
+
+ STRING_VECTOR _apriori_argv;
+ _apriori_argv.push_back(std::string("Empty"));
+ __parse_argument_vector(_apriori_argv);
+}
+
+inline
+GetPot::GetPot(const int argc_, char ** argv_,
+ const char* FieldSeparator /* =0x0 */)
+ // leave 'char**' non-const to honor less capable compilers ...
+{
+ // TODO: Ponder over the problem when the argument list is of size = 0.
+ // This is 'sabotage', but it can still occur if the user specifies
+ // it himself.
+ assert(argc_ >= 1);
+ __basic_initialization();
+
+ // if specified -> overwrite default string
+ if( FieldSeparator ) _field_separator = std::string(FieldSeparator);
+
+ // -- make an internal copy of the argument list:
+ STRING_VECTOR _apriori_argv;
+ // -- for the sake of clarity: we do want to include the first argument in the argument vector !
+ // it will not be a nominus argument, though. This gives us a minimun vector size of one
+ // which facilitates error checking in many functions. Also the user will be able to
+ // retrieve the name of his application by "get[0]"
+ _apriori_argv.push_back(std::string(argv_[0]));
+ int i=1;
+ for(; i<argc_; ++i) {
+ std::string tmp(argv_[i]); // recall the problem with temporaries,
+ _apriori_argv.push_back(tmp); // reference counting in arguement lists ...
+ }
+ __parse_argument_vector(_apriori_argv);
+}
+
+
+inline
+GetPot::GetPot(const char* FileName,
+ const char* CommentStart /* = 0x0 */, const char* CommentEnd /* = 0x0 */,
+ const char* FieldSeparator/* = 0x0 */)
+{
+ __basic_initialization();
+
+ // if specified -> overwrite default strings
+ if( CommentStart ) _comment_start = std::string(CommentStart);
+ if( CommentEnd ) _comment_end = std::string(CommentEnd);
+ if( FieldSeparator ) _field_separator = FieldSeparator;
+
+ STRING_VECTOR _apriori_argv;
+ // -- file name is element of argument vector, however, it is not parsed for
+ // variable assignments or nominuses.
+ _apriori_argv.push_back(std::string(FileName));
+
+ STRING_VECTOR args = __read_in_file(FileName);
+ _apriori_argv.insert(_apriori_argv.begin()+1, args.begin(), args.end());
+ __parse_argument_vector(_apriori_argv);
+}
+
+inline
+GetPot::GetPot(const GetPot& That)
+{ GetPot::operator=(That); }
+
+inline
+GetPot::~GetPot()
+{
+ // may be some return strings had to be created, delete now !
+ victorate(char*, __internal_string_container, it)
+ delete [] *it;
+}
+
+inline GetPot&
+GetPot::operator=(const GetPot& That)
+{
+ if (&That == this) return *this;
+
+ _comment_start = That._comment_start;
+ _comment_end = That._comment_end;
+ argv = That.argv;
+ variables = That.variables;
+ prefix = That.prefix;
+
+ cursor = That.cursor;
+ nominus_cursor = That.nominus_cursor;
+ search_failed_f = That.search_failed_f;
+
+ idx_nominus = That.idx_nominus;
+ search_loop_f = That.search_loop_f;
+
+ return *this;
+}
+
+
+inline void
+GetPot::absorb(const GetPot& That)
+{
+ if (&That == this) return;
+
+ STRING_VECTOR __tmp(That.argv);
+
+ __tmp.erase(__tmp.begin());
+
+ __parse_argument_vector(__tmp);
+}
+
+inline void
+GetPot::clear_requests()
+{
+ _requested_arguments.erase(_requested_arguments.begin(), _requested_arguments.end());
+ _requested_variables.erase(_requested_variables.begin(), _requested_variables.end());
+ _requested_sections.erase(_requested_sections.begin(), _requested_sections.end());
+}
+
+inline void
+GetPot::__parse_argument_vector(const STRING_VECTOR& ARGV)
+{
+ if( ARGV.size() == 0 ) return;
+
+ // build internal databases:
+ // 1) array with no-minus arguments (usually used as filenames)
+ // 2) variable assignments:
+ // 'variable name' '=' number | string
+ STRING_VECTOR section_stack;
+ STRING_VECTOR::const_iterator it = ARGV.begin();
+
+
+ section = "";
+
+ // -- do not parse the first argument, so that it is not interpreted a s a nominus or so.
+ argv.push_back(*it);
+ ++it;
+
+ // -- loop over remaining arguments
+ unsigned i=1;
+ for(; it != ARGV.end(); ++it, ++i) {
+ std::string arg = *it;
+
+ if( arg.length() == 0 ) continue;
+
+ // -- [section] labels
+ if( arg.length() > 1 && arg[0] == '[' && arg[arg.length()-1] == ']' ) {
+
+ // (*) sections are considered 'requested arguments'
+ if( __request_recording_f ) _requested_arguments.push_back(arg);
+
+ const std::string Name = __DBE_expand_string(arg.substr(1, arg.length()-2));
+ section = __process_section_label(Name, section_stack);
+ // new section --> append to list of sections
+ if( find(section_list.begin(), section_list.end(), section) == section_list.end() )
+ if( section.length() != 0 ) section_list.push_back(section);
+ argv.push_back(arg);
+ }
+ else {
+ arg = section + __DBE_expand_string(arg);
+ argv.push_back(arg);
+ }
+
+ // -- separate array for nominus arguments
+ if( arg[0] != '-' ) idx_nominus.push_back(unsigned(i));
+
+ // -- variables: does arg contain a '=' operator ?
+ const char* p = arg.c_str();
+ for(; *p ; p++) {
+ if( *p == '=' ) {
+ // (*) record for later ufo detection
+ // arguments carriying variables are always treated as 'requested' arguments.
+ // as a whole! That is 'x=4712' is considered a requested argument.
+ //
+ // unrequested variables have to be detected with the ufo-variable
+ // detection routine.
+ if( __request_recording_f ) _requested_arguments.push_back(arg);
+
+ // set terminating 'zero' to treat first part as single string
+ // => arg (from start to 'p') = Name of variable
+ // p+1 (until terminating zero) = value of variable
+ char* o = (char*)p++;
+ *o = '\0'; // set temporary terminating zero
+ // __set_variable(...)
+ // calls __find_variable(...) which registers the search
+ // temporarily disable this
+ const bool tmp = __request_recording_f;
+ __request_recording_f = false;
+ __set_variable(arg.c_str(), p); // v-name = c_str() bis 'p', value = rest
+ __request_recording_f = tmp;
+ *o = '='; // reset the original '='
+ break;
+ }
+ }
+ }
+}
+
+
+inline STRING_VECTOR
+GetPot::__read_in_file(const char* FileName)
+{
+ std::ifstream i(FileName);
+ if( ! i ) return STRING_VECTOR();
+ // argv[0] == the filename of the file that was read in
+ return __read_in_stream(i);
+}
+
+inline STRING_VECTOR
+GetPot::__read_in_stream(std::istream& istr)
+{
+ STRING_VECTOR brute_tokens;
+ while(istr) {
+ __skip_whitespace(istr);
+
+ const std::string Token = __get_next_token(istr);
+ if( Token.length() == 0 || Token[0] == EOF) break;
+ brute_tokens.push_back(Token);
+ }
+
+ // -- reduce expressions of token1'='token2 to a single
+ // string 'token1=token2'
+ // -- copy everything into 'argv'
+ // -- arguments preceded by something like '[' name ']' (section)
+ // produce a second copy of each argument with a prefix '[name]argument'
+ unsigned i1 = 0;
+ unsigned i2 = 1;
+ unsigned i3 = 2;
+
+ STRING_VECTOR arglist;
+ while( i1 < brute_tokens.size() ) {
+ const std::string& SRef = brute_tokens[i1];
+ // 1) concatinate 'abcdef' '=' 'efgasdef' to 'abcdef=efgasdef'
+ // note: java.lang.String: substring(a,b) = from a to b-1
+ // C++ string: substr(a,b) = from a to a + b
+ if( i2 < brute_tokens.size() && brute_tokens[i2] == "=" ) {
+ if( i3 >= brute_tokens.size() )
+ arglist.push_back(brute_tokens[i1] + brute_tokens[i2]);
+ else
+ arglist.push_back(brute_tokens[i1] + brute_tokens[i2] + brute_tokens[i3]);
+ i1 = i3+1; i2 = i3+2; i3 = i3+3;
+ continue;
+ }
+ else {
+ arglist.push_back(SRef);
+ i1=i2; i2=i3; i3++;
+ }
+ }
+ return arglist;
+}
+
+inline void
+GetPot::__skip_whitespace(std::istream& istr)
+ // find next non-whitespace while deleting comments
+{
+ int tmp = istr.get();
+ do {
+ // -- search a non whitespace
+ while( isspace(tmp) ) {
+ tmp = istr.get();
+ if( ! istr ) return;
+ }
+
+ // -- look if characters match the comment starter string
+ const std::istream::pos_type Pos = istr.tellg();
+ unsigned i=0;
+ for(; i<_comment_start.length() ; ++i) {
+ if( tmp != _comment_start[i] ) {
+// HACK: The following line throws off msvc8:
+// istr.seekg(Pos);
+ // -- one step more backwards, since 'tmp' already at non-whitespace
+ istr.unget();
+ return;
+ }
+ tmp = istr.get();
+ if( ! istr ) { istr.unget(); return; }
+ }
+ // 'tmp' contains last character of _comment_starter
+
+ // -- comment starter found -> search for comment ender
+ unsigned match_no=0;
+ while(1+1 == 2) {
+ tmp = istr.get();
+ if( ! istr ) { istr.unget(); return; }
+
+ if( tmp == _comment_end[match_no] ) {
+ match_no++;
+ if( match_no == _comment_end.length() ) {
+ istr.unget();
+ break; // shuffle more whitespace, end of comment found
+ }
+ }
+ else
+ match_no = 0;
+ }
+
+ tmp = istr.get();
+
+ } while( istr );
+ istr.unget();
+}
+
+inline const std::string
+GetPot::__get_next_token(std::istream& istr)
+ // get next concatinates string token. consider quotes that embrace
+ // whitespaces
+{
+ std::string token;
+ int tmp = 0;
+ int last_letter = 0;
+ while(1+1 == 2) {
+ last_letter = tmp; tmp = istr.get();
+ if( tmp == EOF
+ || ((tmp == ' ' || tmp == '\t' || tmp == '\n') && last_letter != '\\') ) {
+ return token;
+ }
+ else if( tmp == '\'' && last_letter != '\\' ) {
+ // QUOTES: un-backslashed quotes => it's a string
+ token += __get_string(istr);
+ continue;
+ }
+ else if( tmp == '{' && last_letter == '$') {
+ token += '{' + __get_until_closing_bracket(istr);
+ continue;
+ }
+ else if( tmp == '$' && last_letter == '\\') {
+ token += tmp; tmp = 0; // so that last_letter will become = 0, not '$';
+ continue;
+ }
+ else if( tmp == '\\' && last_letter != '\\')
+ continue; // don't append un-backslashed backslashes
+ token += tmp;
+ }
+}
+
+inline const std::string
+GetPot::__get_string(std::istream& istr)
+ // parse input until next matching '
+{
+ std::string str;
+ int tmp = 0;
+ int last_letter = 0;
+ while(1 + 1 == 2) {
+ last_letter = tmp; tmp = istr.get();
+ if( tmp == EOF) return str;
+ // un-backslashed quotes => it's the end of the string
+ else if( tmp == '\'' && last_letter != '\\') return str;
+ else if( tmp == '\\' && last_letter != '\\') continue; // don't append
+
+ str += tmp;
+ }
+}
+
+inline const std::string
+GetPot::__get_until_closing_bracket(std::istream& istr)
+ // parse input until next matching }
+{
+ std::string str = "";
+ int tmp = 0;
+ int last_letter = 0;
+ int brackets = 1;
+ while(1 + 1 == 2) {
+ last_letter = tmp; tmp = istr.get();
+ if( tmp == EOF) return str;
+ else if( tmp == '{' && last_letter == '$') brackets += 1;
+ else if( tmp == '}') {
+ brackets -= 1;
+ // un-backslashed brackets => it's the end of the string
+ if( brackets == 0) return str + '}';
+ else if( tmp == '\\' && last_letter != '\\')
+ continue; // do not append an unbackslashed backslash
+ }
+ str += tmp;
+ }
+}
+
+inline std::string
+GetPot::__process_section_label(const std::string& Section,
+ STRING_VECTOR& section_stack)
+{
+ std::string sname = Section;
+ // 1) subsection of actual section ('./' prefix)
+ if( sname.length() >= 2 && sname.substr(0, 2) == "./" ) {
+ sname = sname.substr(2);
+ }
+ // 2) subsection of parent section ('../' prefix)
+ else if( sname.length() >= 3 && sname.substr(0, 3) == "../" ) {
+ do {
+ if( section_stack.end() != section_stack.begin() )
+ section_stack.pop_back();
+ sname = sname.substr(3);
+ } while( sname.substr(0, 3) == "../" );
+ }
+ // 3) subsection of the root-section
+ else {
+ section_stack.erase(section_stack.begin(), section_stack.end());
+ // [] => back to root section
+ }
+
+ if( sname != "" ) {
+ // parse section name for 'slashes'
+ unsigned i=0;
+ while( i < sname.length() ) {
+ if( sname[i] == '/' ) {
+ section_stack.push_back(sname.substr(0,i));
+ if( i+1 < sname.length()-1 )
+ sname = sname.substr(i+1);
+ i = 0;
+ }
+ else
+ ++i;
+ }
+ section_stack.push_back(sname);
+ }
+ std::string section = "";
+ if( section_stack.size() != 0 ) {
+ victorate(std::string, section_stack, it)
+ section += *it + "/";
+ }
+ return section;
+}
+
+
+// convert string to DOUBLE, if not possible return Default
+inline double
+GetPot::__convert_to_type(const std::string& String, double Default) const
+{
+ double tmp;
+ if( sscanf(String.c_str(),"%lf", &tmp) != 1 ) return Default;
+ return tmp;
+}
+
+// convert string to INT, if not possible return Default
+inline int
+GetPot::__convert_to_type(const std::string& String, int Default) const
+{
+ // NOTE: intermediate results may be floating points, so that the string
+ // may look like 2.0e1 (i.e. float format) => use float conversion
+ // in any case.
+ return (int)__convert_to_type(String, (double)Default);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// (*) cursor oriented functions
+//.............................................................................
+inline const std::string
+GetPot::__get_remaining_string(const std::string& String, const std::string& Start) const
+ // Checks if 'String' begins with 'Start' and returns the remaining String.
+ // Returns None if String does not begin with Start.
+{
+ if( Start == "" ) return String;
+ // note: java.lang.String: substring(a,b) = from a to b-1
+ // C++ string: substr(a,b) = from a to a + b
+ if( String.find(Start) == 0 ) return String.substr(Start.length());
+ else return "";
+}
+
+// -- search for a certain argument and set cursor to position
+inline bool
+GetPot::search(const char* Option)
+{
+ unsigned OldCursor = cursor;
+ const std::string SearchTerm = prefix + Option;
+
+ // (*) record requested arguments for later ufo detection
+ __record_argument_request(SearchTerm);
+
+ if( OldCursor >= argv.size() ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
+ search_failed_f = true;
+
+ // (*) first loop from cursor position until end
+ unsigned c = cursor;
+ for(; c < argv.size(); c++) {
+ if( argv[c] == SearchTerm )
+ { cursor = c; search_failed_f = false; return true; }
+ }
+ if( ! search_loop_f ) return false;
+
+ // (*) second loop from 0 to old cursor position
+ for(c = 1; c < OldCursor; c++) {
+ if( argv[c] == SearchTerm )
+ { cursor = c; search_failed_f = false; return true; }
+ }
+ // in case nothing is found the cursor stays where it was
+ return false;
+}
+
+
+inline bool
+GetPot::search(unsigned No, const char* P, ...)
+{
+ // (*) recording the requested arguments happens in subroutine 'search'
+ if( No == 0 ) return false;
+
+ // search for the first argument
+ if( search(P) == true ) return true;
+
+ // start interpreting variable argument list
+ va_list ap;
+ va_start(ap, P);
+ unsigned i = 1;
+ for(; i < No; ++i) {
+ char* Opt = va_arg(ap, char *);
+ if( search(Opt) == true ) break;
+ }
+
+ if( i < No ) {
+ ++i;
+ // loop was left before end of array --> hit but
+ // make sure that the rest of the search terms is marked
+ // as requested.
+ for(; i < No; ++i) {
+ char* Opt = va_arg(ap, char *);
+ // (*) record requested arguments for later ufo detection
+ __record_argument_request(Opt);
+ }
+ va_end(ap);
+ return true;
+ }
+
+ va_end(ap);
+ // loop was left normally --> no hit
+ return false;
+}
+
+inline void
+GetPot::reset_cursor()
+{ search_failed_f = false; cursor = 0; }
+
+inline void
+GetPot::init_multiple_occurrence()
+{ disable_loop(); reset_cursor(); }
+///////////////////////////////////////////////////////////////////////////////
+// (*) direct access to command line arguments
+//.............................................................................
+//
+inline const std::string
+GetPot::operator[](unsigned idx) const
+{ return idx < argv.size() ? argv[idx] : ""; }
+
+inline int
+GetPot::get(unsigned Idx, int Default) const
+{
+ if( Idx >= argv.size() ) return Default;
+ return __convert_to_type(argv[Idx], Default);
+}
+
+inline double
+GetPot::get(unsigned Idx, const double& Default) const
+{
+ if( Idx >= argv.size() ) return Default;
+ return __convert_to_type(argv[Idx], Default);
+}
+
+inline const std::string
+GetPot::get(unsigned Idx, const char* Default) const
+{
+ if( Idx >= argv.size() ) return Default;
+ else return argv[Idx];
+}
+
+inline unsigned
+GetPot::size() const
+{ return static_cast<unsigned int>(argv.size()); }
+
+
+// -- next() function group
+inline int
+GetPot::next(int Default)
+{
+ if( search_failed_f ) return Default;
+ cursor++;
+ if( cursor >= argv.size() )
+ { cursor = static_cast<unsigned int>(argv.size()); return Default; }
+
+ // (*) record requested argument for later ufo detection
+ __record_argument_request(argv[cursor]);
+
+ const std::string Remain = __get_remaining_string(argv[cursor], prefix);
+
+ return Remain != "" ? __convert_to_type(Remain, Default) : Default;
+}
+
+inline double
+GetPot::next(const double& Default)
+{
+ if( search_failed_f ) return Default;
+ cursor++;
+
+ if( cursor >= argv.size() )
+ { cursor = static_cast<unsigned int>(argv.size()); return Default; }
+
+ // (*) record requested argument for later ufo detection
+ __record_argument_request(argv[cursor]);
+
+ std::string Remain = __get_remaining_string(argv[cursor], prefix);
+
+ return Remain != "" ? __convert_to_type(Remain, Default) : Default;
+}
+
+inline const std::string
+GetPot::next(const char* Default)
+{
+ if( search_failed_f ) return Default;
+ cursor++;
+
+ if( cursor >= argv.size() )
+ { cursor = static_cast<unsigned int>(argv.size()); return Default; }
+
+ // (*) record requested argument for later ufo detection
+ __record_argument_request(argv[cursor]);
+
+ const std::string Remain = __get_remaining_string(argv[cursor], prefix);
+
+ if( Remain == "" ) return Default;
+
+
+ // (*) function returns a pointer to a char array (inside Remain)
+ // this array will be deleted, though after this function call.
+ // To ensure propper functioning, create a copy inside *this
+ // object and only delete it, when *this is deleted.
+ char* result = new char[Remain.length()+1];
+ strncpy(result, Remain.c_str(), Remain.length()+1);
+
+ // store the created string internally, delete if when object deleted
+ __internal_string_container.push_back(result);
+
+ return result;
+}
+
+// -- follow() function group
+// distinct option to be searched for
+inline int
+GetPot::follow(int Default, const char* Option)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( search(Option) == false ) return Default;
+ return next(Default);
+}
+
+inline double
+GetPot::follow(const double& Default, const char* Option)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( search(Option) == false ) return Default;
+ return next(Default);
+}
+
+inline const std::string
+GetPot::follow(const char* Default, const char* Option)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( search(Option) == false ) return Default;
+ return next(Default);
+}
+
+// -- second follow() function group
+// multiple option to be searched for
+inline int
+GetPot::follow(int Default, unsigned No, const char* P, ...)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( No == 0 ) return Default;
+ if( search(P) == true ) return next(Default);
+
+ va_list ap;
+ va_start(ap, P);
+ unsigned i=1;
+ for(; i<No; ++i) {
+ char* Opt = va_arg(ap, char *);
+ if( search(Opt) == true ) {
+ va_end(ap);
+ return next(Default);
+ }
+ }
+ va_end(ap);
+ return Default;
+}
+
+inline double
+GetPot::follow(const double& Default, unsigned No, const char* P, ...)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( No == 0 ) return Default;
+ if( search(P) == true ) return next(Default);
+
+ va_list ap;
+ va_start(ap, P);
+ for(unsigned i=1; i<No; ++i) {
+ char* Opt = va_arg(ap, char *);
+ if( search(Opt) == true ) {
+ va_end(ap);
+ return next(Default);
+ }
+ }
+ va_end(ap);
+ return Default;
+}
+
+inline const std::string
+GetPot::follow(const char* Default, unsigned No, const char* P, ...)
+{
+ // (*) record requested of argument is entirely handled in 'search()' and 'next()'
+ if( No == 0 ) return Default;
+ if( search(P) == true ) return next(Default);
+
+ va_list ap;
+ va_start(ap, P);
+ unsigned i=1;
+ for(; i<No; ++i) {
+ char* Opt = va_arg(ap, char *);
+ if( search(Opt) == true ) {
+ va_end(ap);
+ return next(Default);
+ }
+ }
+ va_end(ap);
+ return Default;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) lists of nominus following an option
+//.............................................................................
+//
+inline std::vector<std::string>
+GetPot::nominus_followers(const char* Option)
+{
+ std::vector<std::string> result_list;
+ if( search(Option) == false ) return result_list;
+ while( 1 + 1 == 2 ) {
+ ++cursor;
+ if( cursor >= argv.size() ) {
+ cursor = argv.size() - 1;
+ return result_list;
+ }
+ if( argv[cursor].length() >= 1 ) {
+ if( argv[cursor][0] == '-' ) {
+ return result_list;
+ }
+ // -- record for later ufo-detection
+ __record_argument_request(argv[cursor]);
+ // -- append to the result list
+ result_list.push_back(argv[cursor]);
+ }
+ }
+}
+
+inline std::vector<std::string>
+GetPot::nominus_followers(unsigned No, ...)
+{
+ std::vector<std::string> result_list;
+ // (*) record requested of argument is entirely handled in 'search()'
+ // and 'nominus_followers()'
+ if( No == 0 ) return result_list;
+
+ va_list ap;
+ va_start(ap, No);
+ for(unsigned i=0; i<No; ++i) {
+ char* Option = va_arg(ap, char *);
+ std::vector<std::string> tmp = nominus_followers(Option);
+ result_list.insert(result_list.end(), tmp.begin(), tmp.end());
+
+ // std::cerr << "option = '" << Option << "'" << std::endl;
+ // std::cerr << "length = " << tmp.size() << std::endl;
+ // std::cerr << "new result list = <";
+ // for(std::vector<std::string>::const_iterator it = result_list.begin();
+ // it != result_list.end(); ++it)
+ // std::cerr << *it << ", ";
+ // std::cerr << ">\n";
+ }
+ va_end(ap);
+ return result_list;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) directly connected options
+//.............................................................................
+//
+inline int
+GetPot::direct_follow(int Default, const char* Option)
+{
+ const char* FollowStr = __match_starting_string(Option);
+ if( FollowStr == 0x0 ) return Default;
+
+ // (*) record requested of argument for later ufo-detection
+ __record_argument_request(std::string(Option) + FollowStr);
+
+ if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
+ return __convert_to_type(FollowStr, Default);
+}
+
+inline double
+GetPot::direct_follow(const double& Default, const char* Option)
+{
+ const char* FollowStr = __match_starting_string(Option);
+ if( FollowStr == 0 ) return Default;
+
+ // (*) record requested of argument for later ufo-detection
+ __record_argument_request(std::string(Option) + FollowStr);
+
+ if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
+ return __convert_to_type(FollowStr, Default);
+}
+
+inline const std::string
+GetPot::direct_follow(const char* Default, const char* Option)
+{
+ if( search_failed_f ) return Default;
+ const char* FollowStr = __match_starting_string(Option);
+ if( FollowStr == 0 ) return Default;
+
+ // (*) record requested of argument for later ufo-detection
+ if( FollowStr ) __record_argument_request(std::string(Option) + FollowStr);
+
+ if( ++cursor >= static_cast<unsigned int>(argv.size()) ) cursor = static_cast<unsigned int>(argv.size());
+ return std::string(FollowStr);
+}
+
+inline std::vector<std::string>
+GetPot::string_tails(const char* StartString)
+{
+ std::vector<std::string> result;
+ const unsigned N = static_cast<unsigned int>(strlen(StartString));
+
+ std::vector<std::string>::iterator it = argv.begin();
+
+ unsigned idx = 0;
+ while( it != argv.end() ) {
+ // (*) does start string match the given option?
+ // NO -> goto next option
+ if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
+
+ // append the found tail to the result vector
+ result.push_back((*it).substr(N));
+
+ // adapt the nominus vector
+ std::vector<unsigned>::iterator nit = idx_nominus.begin();
+ for(; nit != idx_nominus.end(); ++nit) {
+ if( *nit == idx ) {
+ idx_nominus.erase(nit);
+ for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
+ break;
+ }
+ }
+
+ // erase the found option
+ argv.erase(it);
+
+ // 100% safe solution: set iterator back to the beginning.
+ // (normally, 'it--' would be enough, but who knows how the
+ // iterator is implemented and .erase() definitely invalidates
+ // the current iterator position.
+ if( argv.empty() ) break;
+ it = argv.begin();
+ }
+ cursor = 0;
+ nominus_cursor = -1;
+ return result;
+}
+
+inline std::vector<int>
+GetPot::int_tails(const char* StartString, const int Default /* = -1 */)
+{
+ std::vector<int> result;
+ const unsigned N = static_cast<unsigned int>(strlen(StartString));
+
+ std::vector<std::string>::iterator it = argv.begin();
+
+ unsigned idx = 0;
+ while( it != argv.end() ) {
+ // (*) does start string match the given option?
+ // NO -> goto next option
+ if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
+
+ // append the found tail to the result vector
+ result.push_back(__convert_to_type((*it).substr(N), Default));
+
+ // adapt the nominus vector
+ std::vector<unsigned>::iterator nit = idx_nominus.begin();
+ for(; nit != idx_nominus.end(); ++nit) {
+ if( *nit == idx ) {
+ idx_nominus.erase(nit);
+ for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
+ break;
+ }
+ }
+
+ // erase the found option
+ argv.erase(it);
+
+ // 100% safe solution: set iterator back to the beginning.
+ // (normally, 'it--' would be enough, but who knows how the
+ // iterator is implemented and .erase() definitely invalidates
+ // the current iterator position.
+ if( argv.empty() ) break;
+ it = argv.begin();
+ }
+ cursor = 0;
+ nominus_cursor = -1;
+ return result;
+}
+
+inline std::vector<double>
+GetPot::double_tails(const char* StartString,
+ const double Default /* = -1.0 */)
+{
+ std::vector<double> result;
+ const unsigned N = static_cast<unsigned int>(strlen(StartString));
+
+ std::vector<std::string>::iterator it = argv.begin();
+ unsigned idx = 0;
+ while( it != argv.end() ) {
+ // (*) does start string match the given option?
+ // NO -> goto next option
+ if( strncmp(StartString, (*it).c_str(), N) != 0) { ++it; ++idx; continue; }
+
+ // append the found tail to the result vector
+ result.push_back(__convert_to_type((*it).substr(N), Default));
+
+ // adapt the nominus vector
+ std::vector<unsigned>::iterator nit = idx_nominus.begin();
+ for(; nit != idx_nominus.end(); ++nit) {
+ if( *nit == idx ) {
+ idx_nominus.erase(nit);
+ for(; nit != idx_nominus.end(); ++nit) *nit -= 1;
+ break;
+ }
+ }
+
+ // erase the found option
+ argv.erase(it);
+
+ // 100% safe solution: set iterator back to the beginning.
+ // (normally, 'it--' would be enough, but who knows how the
+ // iterator is implemented and .erase() definitely invalidates
+ // the current iterator position.
+ if( argv.empty() ) break;
+ it = argv.begin();
+ }
+ cursor = 0;
+ nominus_cursor = -1;
+ return result;
+}
+
+
+
+
+
+inline const char*
+GetPot::__match_starting_string(const char* StartString)
+ // pointer to the place where the string after
+ // the match inside the found argument starts.
+ // 0 no argument matches the starting string.
+{
+ const unsigned N = static_cast<unsigned int>(strlen(StartString));
+ unsigned OldCursor = cursor;
+
+ if( OldCursor >= static_cast<unsigned int>(argv.size()) ) OldCursor = static_cast<unsigned int>(argv.size()) - 1;
+ search_failed_f = true;
+
+ // (*) first loop from cursor position until end
+ unsigned c = cursor;
+ for(; c < argv.size(); c++) {
+ if( strncmp(StartString, argv[c].c_str(), N) == 0)
+ { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
+ }
+
+ if( ! search_loop_f ) return false;
+
+ // (*) second loop from 0 to old cursor position
+ for(c = 1; c < OldCursor; c++) {
+ if( strncmp(StartString, argv[c].c_str(), N) == 0)
+ { cursor = c; search_failed_f = false; return &(argv[c].c_str()[N]); }
+ }
+ return 0;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) search for flags
+//.............................................................................
+//
+inline bool
+GetPot::options_contain(const char* FlagList) const
+{
+ // go through all arguments that start with a '-' (but not '--')
+ std::string str;
+ STRING_VECTOR::const_iterator it = argv.begin();
+ for(; it != argv.end(); ++it) {
+ str = __get_remaining_string(*it, prefix);
+
+ if( str.length() >= 2 && str[0] == '-' && str[1] != '-' )
+ if( __check_flags(str, FlagList) ) return true;
+ }
+ return false;
+}
+
+inline bool
+GetPot::argument_contains(unsigned Idx, const char* FlagList) const
+{
+ if( Idx >= argv.size() ) return false;
+
+ // (*) record requested of argument for later ufo-detection
+ // an argument that is checked for flags is considered to be 'requested'
+ ((GetPot*)this)->__record_argument_request(argv[Idx]);
+
+ if( prefix == "" )
+ // search argument for any flag in flag list
+ return __check_flags(argv[Idx], FlagList);
+
+ // if a prefix is set, then the argument index is the index
+ // inside the 'namespace'
+ // => only check list of arguments that start with prefix
+ unsigned no_matches = 0;
+ unsigned i=0;
+ for(; i<argv.size(); ++i) {
+ const std::string Remain = __get_remaining_string(argv[i], prefix);
+ if( Remain != "") {
+ no_matches += 1;
+ if( no_matches == Idx)
+ return __check_flags(Remain, FlagList);
+ }
+ }
+ // no argument in this namespace
+ return false;
+}
+
+inline bool
+GetPot::__check_flags(const std::string& Str, const char* FlagList) const
+{
+ const char* p=FlagList;
+ for(; *p != '\0' ; p++)
+ if( Str.find(*p) != std::string::npos ) return true; // found something
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) nominus arguments
+inline STRING_VECTOR
+GetPot::nominus_vector() const
+ // return vector of nominus arguments
+{
+ STRING_VECTOR nv;
+ std::vector<unsigned>::const_iterator it = idx_nominus.begin();
+ for(; it != idx_nominus.end(); ++it) {
+ nv.push_back(argv[*it]);
+
+ // (*) record for later ufo-detection
+ // when a nominus vector is requested, the entire set of nominus arguments are
+ // tagged as 'requested'
+ ((GetPot*)this)->__record_argument_request(argv[*it]);
+ }
+ return nv;
+}
+
+inline std::string
+GetPot::next_nominus()
+{
+ if( nominus_cursor < int(idx_nominus.size()) - 1 ) {
+ const std::string Tmp = argv[idx_nominus[++nominus_cursor]];
+
+ // (*) record for later ufo-detection
+ __record_argument_request(Tmp);
+
+ // -- cannot use the Tmp variable, since it is temporary and c_str() will return a pointer
+ // to something that does no longer exist.
+ return Tmp;
+ }
+ return std::string("");
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) variables
+//.............................................................................
+//
+inline int
+GetPot::operator()(const char* VarName, int Default) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ return __convert_to_type(sv->original, Default);
+}
+
+inline double
+GetPot::operator()(const char* VarName, const double& Default) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ return __convert_to_type(sv->original, Default);
+}
+
+inline const std::string
+GetPot::operator()(const char* VarName, const char* Default) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ // -- returning a c_str() pointer is OK here, since the variable remains existant,
+ // while 'sv' of course is delete at the end of the function.
+ return sv->original;
+}
+
+inline int
+GetPot::operator()(const char* VarName, int Default, unsigned Idx) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ const std::string* element = sv->get_element(Idx);
+ if( element == 0 ) return Default;
+ return __convert_to_type(*element, Default);
+}
+
+inline double
+GetPot::operator()(const char* VarName, const double& Default, unsigned Idx) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ const std::string* element = sv->get_element(Idx);
+ if( element == 0 ) return Default;
+ return __convert_to_type(*element, Default);
+}
+
+inline const std::string
+GetPot::operator()(const char* VarName, const char* Default, unsigned Idx) const
+{
+ // (*) recording of requested variables happens in '__find_variable()'
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return Default;
+ const std::string* element = sv->get_element(Idx);
+ if( element == 0 ) return Default;
+ return *element;
+}
+
+inline void
+GetPot::__record_argument_request(const std::string& Name)
+{
+ if( ! __request_recording_f ) return;
+
+ // (*) record requested variable for later ufo detection
+ _requested_arguments.push_back(Name);
+
+ // (*) record considered section for ufo detection
+ STRING_VECTOR STree = __get_section_tree(Name);
+ victorate(std::string, STree, it)
+ if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
+ if( section.length() != 0 ) _requested_sections.push_back(*it);
+}
+
+inline void
+GetPot::__record_variable_request(const std::string& Name)
+{
+ if( ! __request_recording_f ) return;
+
+ // (*) record requested variable for later ufo detection
+ _requested_variables.push_back(Name);
+
+ // (*) record considered section for ufo detection
+ STRING_VECTOR STree = __get_section_tree(Name);
+ victorate(std::string, STree, it)
+ if( find(_requested_sections.begin(), _requested_sections.end(), *it) == _requested_sections.end() )
+ if( section.length() != 0 ) _requested_sections.push_back(*it);
+}
+
+// (*) following functions are to be used from 'outside', after getpot has parsed its
+// arguments => append an argument in the argument vector that reflects the addition
+inline void
+GetPot::__set_variable(const char* VarName, const char* Value)
+{
+ const GetPot::variable* Var = __find_variable(VarName);
+ if( Var == 0 ) variables.push_back(variable(VarName, Value, _field_separator.c_str()));
+ else ((GetPot::variable*)Var)->take(Value, _field_separator.c_str());
+}
+
+inline void
+GetPot::set(const char* VarName, const char* Value, const bool Requested /* = yes */)
+{
+ const std::string Arg = prefix + std::string(VarName) + std::string("=") + std::string(Value);
+ argv.push_back(Arg);
+ __set_variable(VarName, Value);
+
+ // if user does not specify the variable as 'not being requested' it will be
+ // considered amongst the requested variables
+ if( Requested ) __record_variable_request(Arg);
+}
+
+inline void
+GetPot::set(const char* VarName, const double& Value, const bool Requested /* = yes */)
+{ __set_variable(VarName, __double2string(Value).c_str()); }
+
+inline void
+GetPot::set(const char* VarName, const int Value, const bool Requested /* = yes */)
+{ __set_variable(VarName, __int2string(Value).c_str()); }
+
+
+inline unsigned
+GetPot::vector_variable_size(const char* VarName) const
+{
+ const variable* sv = __find_variable(VarName);
+ if( sv == 0 ) return 0;
+ return static_cast<unsigned int>(sv->value.size());
+}
+
+inline STRING_VECTOR
+GetPot::get_variable_names() const
+{
+ STRING_VECTOR result;
+ std::vector<GetPot::variable>::const_iterator it = variables.begin();
+ for(; it != variables.end(); ++it) {
+ const std::string Tmp = __get_remaining_string((*it).name, prefix);
+ if( Tmp != "" ) result.push_back(Tmp);
+ }
+ return result;
+}
+
+inline STRING_VECTOR
+GetPot::get_section_names() const
+{ return section_list; }
+
+inline const GetPot::variable*
+GetPot::__find_variable(const char* VarName) const
+{
+ const std::string Name = prefix + VarName;
+
+ // (*) record requested variable for later ufo detection
+ ((GetPot*)this)->__record_variable_request(Name);
+
+ std::vector<variable>::const_iterator it = variables.begin();
+ for(; it != variables.end(); ++it) {
+ if( (*it).name == Name ) return &(*it);
+ }
+ return 0;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) ouput (basically for debugging reasons
+//.............................................................................
+//
+inline int
+GetPot::print() const
+{
+ std::cout << "argc = " << static_cast<unsigned int>(argv.size()) << std::endl;
+ STRING_VECTOR::const_iterator it = argv.begin();
+ for(; it != argv.end(); ++it)
+ std::cout << *it << std::endl;
+ std::cout << std::endl;
+ return 1;
+}
+
+// (*) dollar bracket expressions (DBEs) ------------------------------------
+//
+// 1) Entry Function: __DBE_expand_string()
+// Takes a string such as
+//
+// "${+ ${x} ${y}} Subject-${& ${section} ${subsection}}: ${title}"
+//
+// calls __DBE_expand() for each of the expressions
+//
+// ${+ ${x} ${y}}
+// ${& ${section} ${subsection}}
+// ${Title}
+//
+// and returns the string
+//
+// "4711 Subject-1.01: Mit den Clowns kamen die Schwaene"
+//
+// assuming that
+// x = "4699"
+// y = "12"
+// section = "1."
+// subsection = "01"
+// title = "Mit den Clowns kamen die Schwaene"
+//
+// 2) __DBE_expand():
+//
+// checks for the command, i.e. the 'sign' that follows '${'
+// divides the argument list into sub-expressions using
+// __DBE_get_expr_list()
+//
+// ${+ ${x} ${y}} -> "${x}" "${y}"
+// ${& ${section} ${subsection}} -> "${section}" "${subsection}"
+// ${Title} -> Nothing, variable expansion
+//
+// 3) __DBE_expression_list():
+//
+// builds a vector of unbracketed whitespace separated strings, i.e.
+//
+// " ${Number}.a ${: Das Marmorbild} AB-${& Author= ${Eichendorf}-1870}"
+//
+// is split into a vector
+//
+// [0] ${Number}.a
+// [1] ${: Das Marmorbild}
+// [2] AB-${& Author= ${Eichendorf}}-1870
+//
+// Each sub-expression is expanded using expand().
+//---------------------------------------------------------------------------
+inline std::string
+GetPot::__DBE_expand_string(const std::string str)
+{
+ // Parses for closing operators '${ }' and expands them letting
+ // white spaces and other letters as they are.
+ std::string new_string = "";
+ unsigned open_brackets = 0;
+ unsigned first = 0;
+ unsigned i = 0;
+ for(; i<str.size(); ++i) {
+ if( i < str.size() - 2 && str.substr(i, 2) == "${" ) {
+ if( open_brackets == 0 ) first = i+2;
+ open_brackets++;
+ }
+ else if( str[i] == '}' && open_brackets > 0) {
+ open_brackets -= 1;
+ if( open_brackets == 0 ) {
+ const std::string Replacement = __DBE_expand(str.substr(first, i - first));
+ new_string += Replacement;
+ }
+ }
+ else if( open_brackets == 0 )
+ new_string += str[i];
+ }
+ return new_string;
+}
+
+inline STRING_VECTOR
+GetPot::__DBE_get_expr_list(const std::string str_, const unsigned ExpectedNumber)
+ // ensures that the resulting vector has the expected number
+ // of arguments, but they may contain an error message
+{
+ std::string str = str_;
+ // Separates expressions by non-bracketed whitespaces, expands them
+ // and puts them into a list.
+
+ unsigned i=0;
+ // (1) eat initial whitespaces
+ for(; i < str.size(); ++i)
+ if( ! isspace(str[i]) ) break;
+
+ STRING_VECTOR expr_list;
+ unsigned open_brackets = 0;
+ std::vector<unsigned> start_idx;
+ unsigned start_new_string = i;
+ unsigned l = static_cast<unsigned int>(str.size());
+
+ // (2) search for ${ } expressions ...
+ while( i < l ) {
+ const char letter = str[i];
+ // whitespace -> end of expression
+ if( isspace(letter) && open_brackets == 0) {
+ expr_list.push_back(str.substr(start_new_string, i - start_new_string));
+ bool no_breakout_f = true;
+ for(++i; i < l ; ++i) {
+ if( ! isspace(str[i]) )
+ { no_breakout_f = false; start_new_string = i; break; }
+ }
+ if( no_breakout_f ) {
+ // end of expression list
+ if( expr_list.size() < ExpectedNumber ) {
+ const std::string pre_tmp("<< ${ }: missing arguments>>");
+ STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
+ expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
+ }
+ return expr_list;
+ }
+ }
+
+ // dollar-bracket expression
+ if( str.length() >= i+2 && str.substr(i, 2) == "${" ) {
+ open_brackets++;
+ start_idx.push_back(i+2);
+ }
+ else if( letter == '}' && open_brackets > 0) {
+ int start = start_idx[start_idx.size()-1];
+ start_idx.pop_back();
+ const std::string Replacement = __DBE_expand(str.substr(start, i-start));
+ if( start - 3 < (int)0)
+ str = Replacement + str.substr(i+1);
+ else
+ str = str.substr(0, start-2) + Replacement + str.substr(i+1);
+ l = static_cast<unsigned int>(str.size());
+ i = start + static_cast<unsigned int>(Replacement.size()) - 3;
+ open_brackets--;
+ }
+ ++i;
+ }
+
+ // end of expression list
+ expr_list.push_back(str.substr(start_new_string, i-start_new_string));
+
+ if( expr_list.size() < ExpectedNumber ) {
+ const std::string pre_tmp("<< ${ }: missing arguments>>");
+ STRING_VECTOR tmp(ExpectedNumber - expr_list.size(), pre_tmp);
+ expr_list.insert(expr_list.end(), tmp.begin(), tmp.end());
+ }
+
+ return expr_list;
+}
+
+inline const GetPot::variable*
+GetPot::__DBE_get_variable(std::string VarName)
+{
+ static GetPot::variable ev;
+ std::string secure_Prefix = prefix;
+
+ prefix = section;
+ // (1) first search in currently active section
+ const GetPot::variable* var = __find_variable(VarName.c_str());
+ if( var != 0 ) { prefix = secure_Prefix; return var; }
+
+ // (2) search in root name space
+ prefix = "";
+ var = __find_variable(VarName.c_str());
+ if( var != 0 ) { prefix = secure_Prefix; return var; }
+
+ prefix = secure_Prefix;
+
+ // error occured => variable name == ""
+ char* tmp = new char[VarName.length() + 25];
+#ifndef WIN32
+ snprintf(tmp, (int)sizeof(char)*(VarName.length() + 25),
+#else
+ _snprintf(tmp, sizeof(char)*(VarName.length() + 25),
+#endif
+ "<<${ } variable '%s' undefined>>", VarName.c_str());
+ ev.name = "";
+ ev.original = std::string(tmp);
+ delete [] tmp;
+ return &ev;
+}
+
+inline std::string
+GetPot::__DBE_expand(const std::string expr)
+{
+ // ${: } pure text
+ if( expr[0] == ':' )
+ return expr.substr(1);
+
+ // ${& expr expr ... } text concatination
+ else if( expr[0] == '&' ) {
+ const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 1);
+
+ STRING_VECTOR::const_iterator it = A.begin();
+ std::string result = *it++;
+ for(; it != A.end(); ++it) result += *it;
+
+ return result;
+ }
+
+ // ${<-> expr expr expr} text replacement
+ else if( expr.length() >= 3 && expr.substr(0, 3) == "<->" ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(3), 3);
+ std::string::size_type tmp = 0;
+ const std::string::size_type L = A[1].length();
+ while( (tmp = A[0].find(A[1])) != std::string::npos ) {
+ A[0].replace(tmp, L, A[2]);
+ }
+ return A[0];
+ }
+ // ${+ ...}, ${- ...}, ${* ...}, ${/ ...} expressions
+ else if( expr[0] == '+' ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ STRING_VECTOR::const_iterator it = A.begin();
+ double result = __convert_to_type(*it++, 0.0);
+ for(; it != A.end(); ++it)
+ result += __convert_to_type(*it, 0.0);
+
+ return __double2string(result);
+ }
+ else if( expr[0] == '-' ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ STRING_VECTOR::const_iterator it = A.begin();
+ double result = __convert_to_type(*it++, 0.0);
+ for(; it != A.end(); ++it)
+ result -= __convert_to_type(*it, 0.0);
+
+ return __double2string(result);
+ }
+ else if( expr[0] == '*' ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ STRING_VECTOR::const_iterator it = A.begin();
+ double result = __convert_to_type(*it++, 0.0);
+ for(; it != A.end(); ++it)
+ result *= __convert_to_type(*it, 0.0);
+
+ return __double2string(result);
+ }
+ else if( expr[0] == '/' ) {
+
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ STRING_VECTOR::const_iterator it = A.begin();
+ double result = __convert_to_type(*it++, 0.0);
+ if( result == 0 ) return "0.0";
+ for(; it != A.end(); ++it) {
+ const double Q = __convert_to_type(*it, 0.0);
+ if( Q == 0.0 ) return "0.0";
+ result /= Q;
+ }
+ return __double2string(result);
+ }
+
+ // ${^ ... } power expressions
+ else if( expr[0] == '^' ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ STRING_VECTOR::const_iterator it = A.begin();
+ double result = __convert_to_type(*it++, 0.0);
+ for(; it != A.end(); ++it)
+ result = pow(result, __convert_to_type(*it, 0.0));
+ return __double2string(result);
+ }
+
+ // ${== } ${<= } ${>= } comparisons (return the number of the first 'match'
+ else if( expr.length() >= 2 &&
+ ( expr.substr(0,2) == "==" || expr.substr(0,2) == ">=" ||
+ expr.substr(0,2) == "<=" || expr[0] == '>' || expr[0] == '<')) {
+ // differentiate between two and one sign operators
+ unsigned op = 0;
+ enum { EQ, GEQ, LEQ, GT, LT };
+ if ( expr.substr(0, 2) == "==" ) op = EQ;
+ else if ( expr.substr(0, 2) == ">=" ) op = GEQ;
+ else if ( expr.substr(0, 2) == "<=" ) op = LEQ;
+ else if ( expr[0] == '>' ) op = GT;
+ else /* "<" */ op = LT;
+
+ STRING_VECTOR a;
+ if ( op == GT || op == LT ) a = __DBE_get_expr_list(expr.substr(1), 2);
+ else a = __DBE_get_expr_list(expr.substr(2), 2);
+
+ std::string x_orig = a[0];
+ double x = __convert_to_type(x_orig, 1e37);
+ unsigned i = 1;
+
+ STRING_VECTOR::const_iterator y_orig = a.begin();
+ for(y_orig++; y_orig != a.end(); y_orig++) {
+ double y = __convert_to_type(*y_orig, 1e37);
+
+ // set the strings as reference if one wasn't a number
+ if ( x == 1e37 || y == 1e37 ) {
+ // it's a string comparison
+ if( (op == EQ && x_orig == *y_orig) || (op == GEQ && x_orig >= *y_orig) ||
+ (op == LEQ && x_orig <= *y_orig) || (op == GT && x_orig > *y_orig) ||
+ (op == LT && x_orig < *y_orig) )
+ return __int2string(i);
+ }
+ else {
+ // it's a number comparison
+ if( (op == EQ && x == y) || (op == GEQ && x >= y) ||
+ (op == LEQ && x <= y) || (op == GT && x > y) ||
+ (op == LT && x < y) )
+ return __int2string(i);
+ }
+ ++i;
+ }
+
+ // nothing fulfills the condition => return 0
+ return "0";
+ }
+ // ${?? expr expr} select
+ else if( expr.length() >= 2 && expr.substr(0, 2) == "??" ) {
+ STRING_VECTOR a = __DBE_get_expr_list(expr.substr(2), 2);
+ double x = __convert_to_type(a[0], 1e37);
+ // last element is always the default argument
+ if( x == 1e37 || x < 0 || x >= a.size() - 1 ) return a[a.size()-1];
+
+ // round x to closest integer
+ return a[int(x+0.5)];
+ }
+ // ${? expr expr expr} if then else conditions
+ else if( expr[0] == '?' ) {
+ STRING_VECTOR a = __DBE_get_expr_list(expr.substr(1), 2);
+ if( __convert_to_type(a[0], 0.0) == 1.0 ) return a[1];
+ else if( a.size() > 2 ) return a[2];
+ }
+ // ${! expr} maxro expansion
+ else if( expr[0] == '!' ) {
+ const GetPot::variable* Var = __DBE_get_variable(expr.substr(1));
+ // error
+ if( Var->name == "" ) return std::string(Var->original);
+
+ const STRING_VECTOR A = __DBE_get_expr_list(Var->original, 2);
+ return A[0];
+ }
+ // ${@: } - string subscription
+ else if( expr.length() >= 2 && expr.substr(0,2) == "@:" ) {
+ const STRING_VECTOR A = __DBE_get_expr_list(expr.substr(2), 2);
+ double x = __convert_to_type(A[1], 1e37);
+
+ // last element is always the default argument
+ if( x == 1e37 || x < 0 || x >= A[0].size() - 1)
+ return "<<1st index out of range>>";
+
+ if( A.size() > 2 ) {
+ double y = __convert_to_type(A[2], 1e37);
+ if ( y != 1e37 && y > 0 && y <= A[0].size() - 1 && y > x )
+ return A[0].substr(int(x+0.5), int(y+1.5) - int(x+0.5));
+ else if( y == -1 )
+ return A[0].substr(int(x+0.5));
+ return "<<2nd index out of range>>";
+ }
+ else {
+ char* tmp = new char[2];
+ tmp[0] = A[0][int(x+0.5)]; tmp[1] = '\0';
+ std::string result(tmp);
+ delete [] tmp;
+ return result;
+ }
+ }
+ // ${@ } - vector subscription
+ else if( expr[0] == '@' ) {
+ STRING_VECTOR A = __DBE_get_expr_list(expr.substr(1), 2);
+ const GetPot::variable* Var = __DBE_get_variable(A[0]);
+ // error
+ if( Var->name == "" ) {
+ // make a copy of the string if an error occured
+ // (since the error variable is a static variable inside get_variable())
+ return std::string(Var->original);
+ }
+
+ double x = __convert_to_type(A[1], 1e37);
+
+ // last element is always the default argument
+ if (x == 1e37 || x < 0 || x >= Var->value.size() )
+ return "<<1st index out of range>>";
+
+ if ( A.size() > 2) {
+ double y = __convert_to_type(A[2], 1e37);
+ int begin = int(x+0.5);
+ int end = 0;
+ if ( y != 1e37 && y > 0 && y <= Var->value.size() && y > x)
+ end = int(y+1.5);
+ else if( y == -1 )
+ end = static_cast<unsigned int>(Var->value.size());
+ else
+ return "<<2nd index out of range>>";
+
+ std::string result = *(Var->get_element(begin));
+ int i = begin+1;
+ for(; i < end; ++i)
+ result += std::string(" ") + *(Var->get_element(i));
+ return result;
+ }
+ else
+ return *(Var->get_element(int(x+0.5)));
+ }
+
+ const STRING_VECTOR A = __DBE_get_expr_list(expr, 1);
+ const GetPot::variable* B = __DBE_get_variable(A[0]);
+
+ // make a copy of the string if an error occured
+ // (since the error variable is a static variable inside get_variable())
+ if( B->name == "" ) return std::string(B->original);
+ // (psuggs@pobox.com mentioned to me the warning MSVC++6.0 produces
+ // with: else return B->original (thanks))
+ return B->original;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) unidentified flying objects
+//.............................................................................
+//
+inline bool
+GetPot::__search_string_vector(const STRING_VECTOR& VecStr, const std::string& Str) const
+{
+ victorate(std::string, VecStr, itk) {
+ if( *itk == Str ) return true;
+ }
+ return false;
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_arguments(unsigned Number,
+ const char* KnownArgument1, ...) const
+{
+ STRING_VECTOR known_arguments;
+
+ // (1) create a vector of known arguments
+ if( Number == 0 ) return STRING_VECTOR();
+
+ va_list ap;
+ va_start(ap, KnownArgument1);
+ known_arguments.push_back(std::string(KnownArgument1));
+ unsigned i=1;
+ for(; i<Number; ++i)
+ known_arguments.push_back(std::string(va_arg(ap, char *)));
+ va_end(ap);
+
+ return unidentified_arguments(known_arguments);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_arguments() const
+{ return unidentified_arguments(_requested_arguments); }
+
+inline STRING_VECTOR
+GetPot::unidentified_arguments(const STRING_VECTOR& Knowns) const
+{
+ STRING_VECTOR ufos;
+ STRING_VECTOR::const_iterator it = argv.begin();
+ ++it; // forget about argv[0] (application or filename)
+ for(; it != argv.end(); ++it) {
+ // -- argument belongs to prefixed section ?
+ const std::string arg = __get_remaining_string(*it, prefix);
+ if( arg == "" ) continue;
+
+ // -- check if in list
+ if( __search_string_vector(Knowns, arg) == false)
+ ufos.push_back(*it);
+ }
+ return ufos;
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_options(unsigned Number,
+ const char* KnownOption1, ...) const
+{
+ STRING_VECTOR known_options;
+
+ // (1) create a vector of known arguments
+ if( Number == 0 ) return STRING_VECTOR();
+
+ va_list ap;
+ va_start(ap, KnownOption1);
+ known_options.push_back(std::string(KnownOption1));
+ unsigned i=1;
+ for(; i<Number; ++i)
+ known_options.push_back(std::string(va_arg(ap, char *)));
+ va_end(ap);
+
+ return unidentified_options(known_options);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_options() const
+{
+ // -- every option is an argument.
+ // -- the set of requested arguments contains the set of requested options.
+ // -- IF the set of requested arguments contains unrequested options,
+ // THEN they were requested as 'follow' and 'next' arguments and not as real options.
+ //
+ // => it is not necessary to separate requested options from the list
+ STRING_VECTOR option_list;
+ victorate(std::string, _requested_arguments, it) {
+ const std::string arg = *it;
+ if( arg.length() == 0 ) continue;
+ if( arg[0] == '-' ) option_list.push_back(arg);
+ }
+ return unidentified_options(option_list);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_options(const STRING_VECTOR& Knowns) const
+{
+ STRING_VECTOR ufos;
+ STRING_VECTOR::const_iterator it = argv.begin();
+ ++it; // forget about argv[0] (application or filename)
+ for(; it != argv.end(); ++it) {
+ // -- argument belongs to prefixed section ?
+ const std::string arg = __get_remaining_string(*it, prefix);
+ if( arg == "" ) continue;
+
+ // is argument really an option (starting with '-') ?
+ if( arg.length() < 1 || arg[0] != '-' ) continue;
+
+ if( __search_string_vector(Knowns, arg) == false)
+ ufos.push_back(*it);
+ }
+
+ return ufos;
+}
+
+inline std::string
+GetPot::unidentified_flags(const char* KnownFlagList, int ArgumentNumber=-1) const
+ // Two modes:
+ // ArgumentNumber >= 0 check specific argument
+ // ArgumentNumber == -1 check all options starting with one '-'
+ // for flags
+{
+ std::string ufos;
+ STRING_VECTOR known_arguments;
+ std::string KFL(KnownFlagList);
+
+ // (2) iteration over '-' arguments (options)
+ if( ArgumentNumber == -1 ) {
+ STRING_VECTOR::const_iterator it = argv.begin();
+ ++it; // forget about argv[0] (application or filename)
+ for(; it != argv.end(); ++it) {
+ // -- argument belongs to prefixed section ?
+ const std::string arg = __get_remaining_string(*it, prefix);
+ if( arg == "" ) continue;
+
+ // -- does arguments start with '-' (but not '--')
+ if ( arg.length() < 2 ) continue;
+ else if( arg[0] != '-' ) continue;
+ else if( arg[1] == '-' ) continue;
+
+ // -- check out if flags inside option are contained in KnownFlagList
+ const char* p=arg.c_str();
+ p++; // skip starting minus
+ for(; *p != '\0' ; p++)
+ if( KFL.find(*p) == std::string::npos ) ufos += *p;
+ }
+ }
+ // (1) check specific argument
+ else {
+ // -- only check arguments that start with prefix
+ int no_matches = 0;
+ unsigned i=1;
+ for(; i<argv.size(); ++i) {
+ const std::string Remain = __get_remaining_string(argv[i], prefix);
+ if( Remain != "") {
+ no_matches++;
+ if( no_matches == ArgumentNumber) {
+ // -- the right argument number inside the section is found
+ // => check it for flags
+ const char* p = Remain.c_str();
+ p++; // skip starting minus
+ for(; *p != '\0' ; p++)
+ if( KFL.find(*p) == std::string::npos ) ufos += *p;
+ return ufos;
+ }
+ }
+ }
+ }
+ return ufos;
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_variables(unsigned Number,
+ const char* KnownVariable1, ...) const
+{
+ STRING_VECTOR known_variables;
+
+ // create vector of known arguments
+ if( Number == 0 ) return STRING_VECTOR();
+
+ va_list ap;
+ va_start(ap, KnownVariable1);
+ known_variables.push_back(std::string(KnownVariable1));
+ unsigned i=1;
+ for(; i<Number; ++i)
+ known_variables.push_back(std::string(va_arg(ap, char *)));
+ va_end(ap);
+
+ return unidentified_variables(known_variables);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_variables(const STRING_VECTOR& Knowns) const
+{
+ STRING_VECTOR ufos;
+
+ victorate(GetPot::variable, variables, it) {
+ // -- check if variable has specific prefix
+ const std::string var_name = __get_remaining_string((*it).name, prefix);
+ if( var_name == "" ) continue;
+
+ // -- check if variable is known
+ if( __search_string_vector(Knowns, var_name) == false)
+ ufos.push_back((*it).name);
+ }
+ return ufos;
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_variables() const
+{ return unidentified_variables(_requested_variables); }
+
+
+inline STRING_VECTOR
+GetPot::unidentified_sections(unsigned Number,
+ const char* KnownSection1, ...) const
+{
+ STRING_VECTOR known_sections;
+
+ // (1) create a vector of known arguments
+ if( Number == 0 ) return STRING_VECTOR();
+
+ va_list ap;
+ va_start(ap, KnownSection1);
+ known_sections.push_back(std::string(KnownSection1));
+ unsigned i=1;
+ for(; i<Number; ++i) {
+ std::string tmp = std::string(va_arg(ap, char *));
+ if( tmp.length() == 0 ) continue;
+ if( tmp[tmp.length()-1] != '/' ) tmp += '/';
+ known_sections.push_back(tmp);
+ }
+ va_end(ap);
+
+ return unidentified_sections(known_sections);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_sections() const
+{ return unidentified_sections(_requested_sections); }
+
+inline STRING_VECTOR
+GetPot::unidentified_sections(const STRING_VECTOR& Knowns) const
+{
+ STRING_VECTOR ufos;
+
+ victorate(std::string, section_list, it) {
+ // -- check if section conform to prefix
+ const std::string sec_name = __get_remaining_string(*it, prefix);
+ if( sec_name == "" ) continue;
+
+ // -- check if section is known
+ if( __search_string_vector(Knowns, sec_name) == false )
+ ufos.push_back(*it);
+ }
+
+ return ufos;
+}
+
+
+inline STRING_VECTOR
+GetPot::unidentified_nominuses(unsigned Number, const char* Known, ...) const
+{
+ STRING_VECTOR known_nominuses;
+
+ // create vector of known arguments
+ if( Number == 0 ) return STRING_VECTOR();
+
+ va_list ap;
+ va_start(ap, Known);
+ known_nominuses.push_back(std::string(Known));
+ unsigned i=1;
+ for(; i<Number; ++i) {
+ std::string tmp = std::string(va_arg(ap, char *));
+ if( tmp.length() == 0 ) continue;
+ known_nominuses.push_back(tmp);
+ }
+ va_end(ap);
+
+ return unidentified_nominuses(known_nominuses);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_nominuses() const {
+ // -- every nominus is an argument.
+ // -- the set of requested arguments contains the set of requested nominuss.
+ // -- IF the set of requested arguments contains unrequested nominuss,
+ // THEN they were requested as 'follow' and 'next' arguments and not as real nominuses.
+ //
+ // => it is not necessary to separate requested nominus from the list
+
+ return unidentified_nominuses(_requested_arguments);
+}
+
+inline STRING_VECTOR
+GetPot::unidentified_nominuses(const STRING_VECTOR& Knowns) const
+{
+ STRING_VECTOR ufos;
+
+ // (2) iterate over all arguments
+ STRING_VECTOR::const_iterator it = argv.begin();
+ ++it; // forget about argv[0] (application or filename)
+ for(; it != argv.end(); ++it) {
+ // -- check if nominus part of prefix
+ const std::string arg = __get_remaining_string(*it, prefix);
+ if( arg == "" ) continue;
+
+ if( arg.length() < 1 ) continue;
+ // option ? --> not a nomius
+ if( arg[0] == '-' ) continue;
+ // section ? --> not a real nominus
+ if( arg[0] == '[' && arg[arg.length()-1] == ']' ) continue;
+ // variable definition ? --> not a real nominus
+ bool continue_f = false;
+ unsigned i=0;
+ for(; i<arg.length() ; ++i)
+ if( arg[i] == '=' ) { continue_f = true; break; }
+ if( continue_f ) continue;
+
+ // real nominuses are compared with the given list
+ if( __search_string_vector(Knowns, arg) == false )
+ ufos.push_back(*it);
+ }
+ return ufos;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// (*) variable class
+//.............................................................................
+//
+inline
+GetPot::variable::variable()
+{}
+
+inline
+GetPot::variable::variable(const variable& That)
+{
+#ifdef WIN32
+ operator=(That);
+#else
+ GetPot::variable::operator=(That);
+#endif
+}
+
+
+inline
+GetPot::variable::variable(const char* Name, const char* Value, const char* FieldSeparator)
+ : name(Name)
+{
+ // make a copy of the 'Value'
+ take(Value, FieldSeparator);
+}
+
+inline const std::string*
+GetPot::variable::get_element(unsigned Idx) const
+{ if( Idx >= value.size() ) return 0; else return &(value[Idx]); }
+
+inline void
+GetPot::variable::take(const char* Value, const char* FieldSeparator)
+{
+ original = std::string(Value);
+
+ // separate string by white space delimiters using 'strtok'
+ // thread safe usage of strtok (no static members)
+ char* spt = 0;
+ // make a copy of the 'Value'
+ char* copy = new char[strlen(Value)+1];
+ strcpy(copy, Value);
+ char* follow_token = strtok_r(copy, FieldSeparator, &spt);
+ if( value.size() != 0 ) value.erase(value.begin(), value.end());
+ while(follow_token != 0) {
+ value.push_back(std::string(follow_token));
+ follow_token = strtok_r(NULL, FieldSeparator, &spt);
+ }
+
+ delete [] copy;
+}
+
+inline
+GetPot::variable::~variable()
+{}
+
+inline GetPot::variable&
+GetPot::variable::operator=(const GetPot::variable& That)
+{
+ if( &That != this) {
+ name = That.name;
+ value = That.value;
+ original = That.original;
+ }
+ return *this;
+}
+
+#undef victorate
+
+
+#endif // __include_guard_GETPOT_H__
+
+
+
diff --git a/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt new file mode 100755 index 0000000000..540fa99c8c --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/CMakeLists.txt @@ -0,0 +1,20 @@ +PROJECT(pelib)
+
+# source files for pelib
+SET(pelib_srcs
+ pelib/BoundImportDirectory.cpp
+ pelib/ComHeaderDirectory.cpp
+ pelib/DebugDirectory.cpp
+ pelib/ExportDirectory.cpp
+ pelib/IatDirectory.cpp
+ pelib/MzHeader.cpp
+ pelib/PeFile.cpp
+ pelib/PeHeader.cpp
+ pelib/PeLibAux.cpp
+ pelib/RelocationsDirectory.cpp
+ pelib/ResourceDirectory.cpp
+ pelib/buffer/InputBuffer.cpp
+ pelib/buffer/OutputBuffer.cpp
+)
+
+ADD_LIBRARY(pelib ${pelib_srcs})
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp new file mode 100755 index 0000000000..5b84931838 --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.cpp @@ -0,0 +1,511 @@ +/*
+* BoundImportDirectory.cpp - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#include "PeLibInc.h"
+#include "BoundImportDirectory.h"
+#include <numeric>
+#include <set>
+#include <map>
+
+namespace PeLib
+{
+ /**
+ * Adds another bound import to the BoundImport directory.
+ * @param strModuleName Name of the PE file which will be imported.
+ * @param dwTds Value of the TimeDateStamp of the bound import field.
+ * @param wOmn Value of the OffsetModuleName of the bound import field.
+ * @param wWfr Value of the NumberOfModuleForwarderRefs of the bound import field.
+ **/
+ int BoundImportDirectory::addBoundImport(const std::string& strModuleName, dword dwTds, word wOmn, word wWfr)
+ {
+ for (unsigned int i=0;i<m_vIbd.size();i++)
+ {
+ if (isEqualNc(strModuleName, m_vIbd[i].strModuleName))
+ {
+ return ERROR_DUPLICATE_ENTRY;
+ }
+ }
+
+ PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR ibidCurrent;
+ ibidCurrent.TimeDateStamp = dwTds;
+ ibidCurrent.OffsetModuleName = wOmn;
+ ibidCurrent.NumberOfModuleForwarderRefs = wWfr;
+ PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
+ ibdCurrent.ibdDescriptor = ibidCurrent;
+ ibdCurrent.strModuleName = strModuleName;
+ m_vIbd.push_back(ibdCurrent);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Searches for the first instance of a module with the given modulename.
+ * @param strModuleName The name of a module.
+ * @return The id of the module.
+ **/
+ int BoundImportDirectory::getModuleIndex(const std::string& strModuleName) const
+ {
+ std::vector<PELIB_IMAGE_BOUND_DIRECTORY>::const_iterator Iter = std::find_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName));
+
+ if (Iter == m_vIbd.end())
+ {
+ return ERROR_ENTRY_NOT_FOUND;
+ }
+
+ return static_cast<int>(std::distance(m_vIbd.begin(), Iter));
+ }
+
+ /**
+ * @return Number of files in the current BoundImport directory.
+ **/
+ unsigned int BoundImportDirectory::calcNumberOfModules() const
+ {
+ return static_cast<unsigned int>(m_vIbd.size());
+ }
+
+ int BoundImportDirectory::read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize)
+ {
+ std::vector<PELIB_IMAGE_BOUND_DIRECTORY> currentDirectory;
+
+ do
+ {
+ PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
+
+ inpBuffer >> ibdCurrent.ibdDescriptor.TimeDateStamp;
+ inpBuffer >> ibdCurrent.ibdDescriptor.OffsetModuleName;
+ inpBuffer >> ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;
+
+ if (ibdCurrent.ibdDescriptor.TimeDateStamp == 0 && ibdCurrent.ibdDescriptor.OffsetModuleName == 0 && ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs == 0) break;
+
+ for (int i=0;i<ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs;i++)
+ {
+ PELIB_IMAGE_BOUND_DIRECTORY currentForwarder;
+
+ inpBuffer >> currentForwarder.ibdDescriptor.TimeDateStamp;
+ inpBuffer >> currentForwarder.ibdDescriptor.OffsetModuleName;
+ inpBuffer >> currentForwarder.ibdDescriptor.NumberOfModuleForwarderRefs;
+
+ ibdCurrent.moduleForwarders.push_back(currentForwarder);
+ }
+
+ currentDirectory.push_back(ibdCurrent);
+ ibdCurrent.moduleForwarders.clear();
+ } while (true);
+
+ for (unsigned int i=0;i<currentDirectory.size();i++)
+ {
+ dword wOmn = currentDirectory[i].ibdDescriptor.OffsetModuleName;
+ if (wOmn > dwSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ currentDirectory[i].strModuleName = "";
+ for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
+ {
+ currentDirectory[i].strModuleName += data[wOmn + k];
+ }
+
+ for (unsigned int j=0;j<currentDirectory[i].moduleForwarders.size();j++)
+ {
+ dword wOmn = currentDirectory[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
+
+ if (wOmn > dwSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+// m_vIbd[i].moduleForwarders[j].strModuleName.assign((char*)(&vBimpDir[wOmn]));
+ currentDirectory[i].moduleForwarders[j].strModuleName = "";
+ for (int k=0;data[wOmn + k] != 0 && k + wOmn < dwSize;k++)
+ {
+ currentDirectory[i].moduleForwarders[j].strModuleName += data[wOmn + k];
+ }
+ }
+ }
+
+ std::swap(m_vIbd, currentDirectory);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Reads the BoundImport directory from a PE file.
+ * @param strModuleName The name of the PE file from which the BoundImport directory is read.
+ * @param dwOffset The file offset where the BoundImport directory can be found (see #PeFile::PeHeader::getIDBoundImportRVA).
+ * @param dwSize The size of the BoundImport directory (see #PeFile::PeHeader::getIDBoundImportSize).
+ **/
+ int BoundImportDirectory::read(const std::string& strModuleName, dword dwOffset, unsigned int uiSize)
+ {
+ std::ifstream ifFile(strModuleName.c_str(), std::ios::binary);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ if (fileSize(ifFile) < dwOffset + uiSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(dwOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBimpDir(uiSize);
+ ifFile.read(reinterpret_cast<char*>(&vBimpDir[0]), uiSize);
+
+ InputBuffer inpBuffer(vBimpDir);
+
+ return read(inpBuffer, &vBimpDir[0], uiSize);
+ }
+
+ int BoundImportDirectory::read(unsigned char* pcBuffer, unsigned int uiSize)
+ {
+ std::vector<unsigned char> vBimpDir(pcBuffer, pcBuffer + uiSize);
+ InputBuffer inpBuffer(vBimpDir);
+
+ return read(inpBuffer, &vBimpDir[0], uiSize);
+ }
+
+ unsigned int BoundImportDirectory::totalModules() const
+ {
+ unsigned int modules = static_cast<unsigned int>(m_vIbd.size());
+
+ for (unsigned int i=0;i<m_vIbd.size();i++)
+ {
+ modules += static_cast<unsigned int>(m_vIbd[i].moduleForwarders.size());
+ }
+
+ return modules;
+ }
+
+ /**
+ * Rebuilds the BoundImport directory. The rebuilded BoundImport directory can then be
+ * written back to a PE file.
+ * @param vBuffer Buffer where the rebuilt BoundImport directory will be stored.
+ * @param fMakeValid If this flag is true a valid directory will be produced.
+ **/
+ void BoundImportDirectory::rebuild(std::vector<byte>& vBuffer, bool fMakeValid) const
+ {
+ std::map<std::string, word> filename_offsets;
+
+ OutputBuffer obBuffer(vBuffer);
+
+ word ulNameOffset = static_cast<word>((totalModules() + 1) * PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size());
+
+ for (unsigned int i=0;i<m_vIbd.size();i++)
+ {
+ obBuffer << m_vIbd[i].ibdDescriptor.TimeDateStamp;
+
+ // Recalculate the offsets if a valid directory is wanted.
+ if (fMakeValid)
+ {
+ if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
+ {
+ filename_offsets[m_vIbd[i].strModuleName] = ulNameOffset;
+ obBuffer << ulNameOffset;
+ ulNameOffset += static_cast<word>(m_vIbd[i].strModuleName.size() + 1);
+ }
+ else
+ {
+ obBuffer << filename_offsets[m_vIbd[i].strModuleName];
+ }
+ }
+ else // Otherwise just copy the old values into the buffer.
+ {
+ obBuffer << m_vIbd[i].ibdDescriptor.OffsetModuleName;
+ }
+
+ obBuffer << m_vIbd[i].ibdDescriptor.NumberOfModuleForwarderRefs;
+
+ for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
+ {
+ obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.TimeDateStamp;
+
+ if (fMakeValid)
+ {
+ if (filename_offsets.find(m_vIbd[i].strModuleName) == filename_offsets.end())
+ {
+ filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName] = ulNameOffset;
+ obBuffer << ulNameOffset;
+ ulNameOffset += static_cast<word>(m_vIbd[i].moduleForwarders[j].strModuleName.size() + 1);
+ }
+ else
+ {
+ obBuffer << filename_offsets[m_vIbd[i].moduleForwarders[j].strModuleName];
+ }
+ }
+ else // Otherwise just copy the old values into the buffer.
+ {
+ obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.OffsetModuleName;
+ }
+
+ obBuffer << m_vIbd[i].moduleForwarders[j].ibdDescriptor.NumberOfModuleForwarderRefs;
+ }
+ }
+
+ obBuffer << static_cast<dword>(0);
+ obBuffer << static_cast<word>(0);
+ obBuffer << static_cast<word>(0);
+
+ for (unsigned int i=0;i<m_vIbd.size();i++)
+ {
+ if (filename_offsets.find(m_vIbd[i].strModuleName) != filename_offsets.end())
+ {
+ obBuffer.add(getModuleName(i).c_str(), static_cast<unsigned long>(getModuleName(i).size() + 1));
+ filename_offsets.erase(m_vIbd[i].strModuleName);
+ }
+
+ for (int j=0;j<calcNumberOfModuleForwarderRefs(i);j++)
+ {
+ if (filename_offsets.find(getModuleName(i, j)) != filename_offsets.end())
+ {
+ obBuffer.add(getModuleName(i, j).c_str(), static_cast<unsigned long>(getModuleName(i, j).size() + 1));
+ filename_offsets.erase(getModuleName(i, j));
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes all bound import files.
+ **/
+ void BoundImportDirectory::clear()
+ {
+ m_vIbd.clear();
+ }
+
+ /**
+ * Removes a field specified by the parameter filename from the BoundImport directory.
+ * @param strModuleName Name of the file whose field will be removed from the BoundImport directory.
+ **/
+ void BoundImportDirectory::removeBoundImport(const std::string& strModuleName)
+ {
+ m_vIbd.erase(std::remove_if(m_vIbd.begin(), m_vIbd.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_BOUND_DIRECTORY::equal), strModuleName)), m_vIbd.end());
+ }
+
+ /**
+ * Returns the size of the rebuilt BoundImportDirectory.
+ * @return Size of the rebuilt BoundImportDirectory.
+ **/
+ unsigned int BoundImportDirectory::size() const
+ {
+ unsigned int size = PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
+
+ std::set<std::string> filenames;
+
+ for (unsigned int i = 0; i < m_vIbd.size(); i++)
+ {
+ filenames.insert(m_vIbd[i].strModuleName);
+
+ size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
+
+ for (unsigned int j = 0; j < m_vIbd[i].moduleForwarders.size(); j++)
+ {
+ filenames.insert(m_vIbd[i].moduleForwarders[j].strModuleName);
+
+ size += PELIB_IMAGE_BOUND_IMPORT_DESCRIPTOR::size();
+ }
+ }
+
+ for (std::set<std::string>::iterator iter = filenames.begin(); iter != filenames.end(); ++iter)
+ {
+ size += static_cast<unsigned int>(iter->size()) + 1;
+ }
+
+ return size;
+ }
+
+ /**
+ * @param strFilename Name of the file.
+ * @param dwOffset File offset the bound importdirectory will be written to.
+ * @param fMakeValid If this flag is true a valid directory will be produced.
+ **/
+ int BoundImportDirectory::write(const std::string& strFilename, dword dwOffset, bool fMakeValid) const
+ {
+ std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
+
+ if (!ofFile)
+ {
+ ofFile.clear();
+ ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
+ }
+ else
+ {
+ ofFile.close();
+ ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
+ }
+
+ if (!ofFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ ofFile.seekp(dwOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBuffer;
+ rebuild(vBuffer, fMakeValid);
+
+ ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<std::streamsize>(vBuffer.size()));
+
+ ofFile.close();
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Retrieves the value of the TimeDateStamp value of a bound import field.
+ * @param dwBidnr Number of the bound import field.
+ * @return Value of the TimeDateStamp of the bound import field.
+ **/
+ dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr) const
+ {
+ return m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp;
+ }
+
+ /**
+ * Retrieves the value of the OffsetModuleName value of a bound import field.
+ * @param dwBidnr Number of the bound import field.
+ * @return Value of the OffsetModuleName of the bound import field.
+ **/
+ word BoundImportDirectory::getOffsetModuleName(dword dwBidnr) const
+ {
+ return m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName;
+ }
+
+ /**
+ * Retrieves the value of the NumberOfModuleForwarderRefs value of a bound import field.
+ * @param dwBidnr Number of the bound import field.
+ * @return Value of the NumberOfModuleForwarderRefs of the bound import field.
+ **/
+ word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr) const
+ {
+ return m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs;
+ }
+
+ /**
+ * Retrieves the value of the ModuleName value of a bound import field.
+ * @param dwBidnr Number of the bound import field.
+ * @return Value of the ModuleName of the bound import field.
+ **/
+ std::string BoundImportDirectory::getModuleName(dword dwBidnr) const
+ {
+ return m_vIbd[dwBidnr].strModuleName;
+ }
+
+ /**
+ * Changes the TimeDateStamp value of an existing bound import field.
+ * @param dwBidnr Number of the bound import field which will be changed.
+ * @param dwTds New value of the TimeDateStamp of the bound import field.
+ **/
+ void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword dwTds)
+ {
+ m_vIbd[dwBidnr].ibdDescriptor.TimeDateStamp = dwTds;
+ }
+
+ /**
+ * Changes the OffsetModuleName value of an existing bound import field.
+ * @param dwBidnr Number of the bound import field which will be changed.
+ * @param wOmn New value of the OffsetModuleName of the bound import field.
+ **/
+ void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, word wOmn)
+ {
+ m_vIbd[dwBidnr].ibdDescriptor.OffsetModuleName = wOmn;
+ }
+
+ /**
+ * Changes the NumberOfModuleForwarderRefs value of an existing bound import field.
+ * @param dwBidnr Number of the bound import field which will be changed.
+ * @param wMfr New value of the NumberOfModuleForwarderRefs of the bound import field.
+ **/
+ void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr)
+ {
+ m_vIbd[dwBidnr].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
+ }
+
+ /**
+ * Changes the ModuleName value of an existing bound import field.
+ * @param dwBidnr Number of the bound import field which will be changed.
+ * @param strModuleName New value of the ModuleName of the bound import field.
+ **/
+ void BoundImportDirectory::setModuleName(dword dwBidnr, const std::string& strModuleName)
+ {
+ m_vIbd[dwBidnr].strModuleName = strModuleName;
+ }
+
+ dword BoundImportDirectory::getTimeDateStamp(dword dwBidnr, dword forwardedModule) const
+ {
+ return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp;
+ }
+
+ word BoundImportDirectory::getOffsetModuleName(dword dwBidnr, dword forwardedModule) const
+ {
+ return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName;
+ }
+
+ word BoundImportDirectory::getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const
+ {
+ return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs;
+ }
+
+ std::string BoundImportDirectory::getModuleName(dword dwBidnr, dword forwardedModule) const
+ {
+ return m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName;
+ }
+
+ void BoundImportDirectory::setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds)
+ {
+ m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.TimeDateStamp = dwTds;
+ }
+
+ void BoundImportDirectory::setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn)
+ {
+ m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.OffsetModuleName = wOmn;
+ }
+
+ void BoundImportDirectory::setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr)
+ {
+ m_vIbd[dwBidnr].moduleForwarders[forwardedModule].ibdDescriptor.NumberOfModuleForwarderRefs = wMfr;
+ }
+
+ void BoundImportDirectory::setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName)
+ {
+ m_vIbd[dwBidnr].moduleForwarders[forwardedModule].strModuleName = strModuleName;
+ }
+
+ word BoundImportDirectory::calcNumberOfModuleForwarderRefs(dword dwBidnr) const
+ {
+ return static_cast<word>(m_vIbd[dwBidnr].moduleForwarders.size());
+ }
+
+ void BoundImportDirectory::addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp, word offsetModuleName, word forwardedModules)
+ {
+ // XXX: Maybe test if there are already 0xFFFF forwarded modules.
+ // XXX: Check for duplicate entries. Is it also necessary to check
+ // non-forwarded entries and forwarded entries in other non-forwarded
+ // entries?
+ // XXX: Can forwarders forward recursively?
+
+ PELIB_IMAGE_BOUND_DIRECTORY ibdCurrent;
+ ibdCurrent.strModuleName = name;
+ ibdCurrent.ibdDescriptor.TimeDateStamp = timeStamp;
+ ibdCurrent.ibdDescriptor.OffsetModuleName = offsetModuleName;
+ ibdCurrent.ibdDescriptor.NumberOfModuleForwarderRefs = forwardedModules;
+
+ m_vIbd[dwBidnr].moduleForwarders.push_back(ibdCurrent);
+ }
+
+ void BoundImportDirectory::removeForwardedModule(dword dwBidnr, word forwardedModule)
+ {
+ m_vIbd[dwBidnr].moduleForwarders.erase(m_vIbd[dwBidnr].moduleForwarders.begin() + forwardedModule);
+ }
+}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h new file mode 100755 index 0000000000..fd2bab56fd --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/BoundImportDirectory.h @@ -0,0 +1,87 @@ +/*
+* BoundImportDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef BOUNDIMPORTDIRECTORY_H
+#define BOUNDIMPORTDIRECTORY_H
+
+#include "PeLibAux.h"
+
+namespace PeLib
+{
+ /// Class that handles the BoundImport directory.
+ /**
+ * This class can read and modify the BoundImport directory table of a PE file.
+ **/
+ class BoundImportDirectory
+ {
+ private:
+ std::vector<PELIB_IMAGE_BOUND_DIRECTORY> m_vIbd; ///< Stores the individual BoundImport fields.
+
+ int read(InputBuffer& inpBuffer, unsigned char* data, unsigned int dwSize);
+ unsigned int totalModules() const;
+ public:
+ /// Adds another bound import.
+ int addBoundImport(const std::string& strModuleName, dword dwTds, word dwOmn, word wWfr); // EXPORT
+ /// Identifies a module through it's name.
+ int getModuleIndex(const std::string& strModuleName) const; // EXPORT
+ /// Returns the number of files in the BoundImport directory.
+ unsigned int calcNumberOfModules() const; // EXPORT
+ /// Reads the BoundImport directory table from a PE file.
+ int read(const std::string& strFileName, dword dwOffset, unsigned int uiSize); // EXPORT
+ int read(unsigned char* pcBuffer, unsigned int uiSize); // EXPORT
+ /// Rebuilds the BoundImport directory.
+ void rebuild(std::vector<byte>& vBuffer, bool fMakeValid = true) const; // EXPORT
+ /// Empties the BoundImport directory.
+ void clear(); // EXPORT
+ /// Removes a bound import.
+ void removeBoundImport(const std::string& strModuleName); // EXPORT
+ /// Returns the size of the BoundImport directory.
+ unsigned int size() const; // EXPORT
+ /// Writes the current bound import directory to a file.
+ int write(const std::string& strFilename, dword dwOffset, bool fMakeValid = true) const; // EXPORT
+
+ /// Retrieves the TimeDateStamp value of a bound import.
+ dword getTimeDateStamp(dword dwBidnr) const; // EXPORT
+ /// Retrieves the OffsetModuleName value of a bound import.
+ word getOffsetModuleName(dword dwBidnr) const; // EXPORT
+ /// Retrieves the NumberOfModuleForwarderRefs value of a bound import.
+ word getNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
+ /// Retrieves the ModuleName value of a bound import.
+ std::string getModuleName(dword dwBidnr) const; // EXPORT
+
+ /// Updates the TimeDateStamp value of a bound import.
+ void setTimeDateStamp(dword dwBidnr, dword dwTds); // EXPORT
+ /// Updates the OffsetModuleName value of a bound import.
+ void setOffsetModuleName(dword dwBidnr, word wOmn); // EXPORT
+ /// Updates the NumberOfModuleForwarderRefs value of a bound import.
+ void setNumberOfModuleForwarderRefs(dword dwBidnr, word wMfr); // EXPORT
+ /// Updates the ModuleName value of a bound import.
+ void setModuleName(dword dwBidnr, const std::string& strModuleName); // EXPORT
+
+ dword getTimeDateStamp(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
+ word getOffsetModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
+ word getNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
+ std::string getModuleName(dword dwBidnr, dword forwardedModule) const; // EXPORT _module
+
+ void setTimeDateStamp(dword dwBidnr, dword forwardedModule, dword dwTds); // EXPORT _module
+ void setOffsetModuleName(dword dwBidnr, dword forwardedModule, word wOmn); // EXPORT _module
+ void setNumberOfModuleForwarderRefs(dword dwBidnr, dword forwardedModule, word wMfr); // EXPORT _module
+ void setModuleName(dword dwBidnr, dword forwardedModule, const std::string& strModuleName); // EXPORT _module
+
+ word calcNumberOfModuleForwarderRefs(dword dwBidnr) const; // EXPORT
+ void addForwardedModule(dword dwBidnr, const std::string& name, dword timeStamp = 0, word offsetModuleName = 0, word forwardedModules = 0); // EXPORT
+ void removeForwardedModule(dword dwBidnr, word forwardedModule); // EXPORT
+ };
+}
+
+
+#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp new file mode 100755 index 0000000000..886348994e --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.cpp @@ -0,0 +1,467 @@ +/*
+* ComHeaderDirectory.cpp - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#include "PeLibInc.h"
+#include "ComHeaderDirectory.h"
+
+namespace PeLib
+{
+ void ComHeaderDirectory::read(InputBuffer& inputbuffer)
+ {
+ PELIB_IMAGE_COR20_HEADER ichCurr;
+
+ inputbuffer >> ichCurr.cb;
+ inputbuffer >> ichCurr.MajorRuntimeVersion;
+ inputbuffer >> ichCurr.MinorRuntimeVersion;
+ inputbuffer >> ichCurr.MetaData.VirtualAddress;
+ inputbuffer >> ichCurr.MetaData.Size;
+ inputbuffer >> ichCurr.Flags;
+ inputbuffer >> ichCurr.EntryPointToken;
+ inputbuffer >> ichCurr.Resources.VirtualAddress;
+ inputbuffer >> ichCurr.Resources.Size;
+ inputbuffer >> ichCurr.StrongNameSignature.VirtualAddress;
+ inputbuffer >> ichCurr.StrongNameSignature.Size;
+ inputbuffer >> ichCurr.CodeManagerTable.VirtualAddress;
+ inputbuffer >> ichCurr.CodeManagerTable.Size;
+ inputbuffer >> ichCurr.VTableFixups.VirtualAddress;
+ inputbuffer >> ichCurr.VTableFixups.Size;
+ inputbuffer >> ichCurr.ExportAddressTableJumps.VirtualAddress;
+ inputbuffer >> ichCurr.ExportAddressTableJumps.Size;
+ inputbuffer >> ichCurr.ManagedNativeHeader.VirtualAddress;
+ inputbuffer >> ichCurr.ManagedNativeHeader.Size;
+
+ std::swap(ichCurr, m_ichComHeader);
+ }
+
+ int ComHeaderDirectory::read(unsigned char* buffer, unsigned int buffersize)
+ {
+ if (buffersize < PELIB_IMAGE_COR20_HEADER::size())
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ std::vector<byte> vComDescDirectory(buffer, buffer + buffersize);
+
+ InputBuffer ibBuffer(vComDescDirectory);
+ read(ibBuffer);
+ return NO_ERROR;
+ }
+
+ /**
+ * Reads a file's COM+ descriptor.
+ * @param strFilename Name of the file.
+ * @param uiOffset File offset of the COM+ descriptor.
+ * @param uiSize Size of the COM+ descriptor.
+ **/
+ int ComHeaderDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
+ {
+ std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
+ unsigned int ulFileSize = fileSize(ifFile);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ if (ulFileSize < uiOffset + uiSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(uiOffset, std::ios::beg);
+
+ std::vector<byte> vComDescDirectory(uiSize);
+ ifFile.read(reinterpret_cast<char*>(&vComDescDirectory[0]), uiSize);
+
+ InputBuffer ibBuffer(vComDescDirectory);
+ read(ibBuffer);
+ return NO_ERROR;
+ }
+
+ /**
+ * Rebuilds the current COM+ descriptor.
+ * @param vBuffer Buffer where the COM+ descriptor will be written to.
+ **/
+ void ComHeaderDirectory::rebuild(std::vector<byte>& vBuffer) const
+ {
+ OutputBuffer obBuffer(vBuffer);
+
+ obBuffer << m_ichComHeader.cb;
+ obBuffer << m_ichComHeader.MajorRuntimeVersion;
+ obBuffer << m_ichComHeader.MinorRuntimeVersion;
+ obBuffer << m_ichComHeader.MetaData.VirtualAddress;
+ obBuffer << m_ichComHeader.MetaData.Size;
+ obBuffer << m_ichComHeader.Flags;
+ obBuffer << m_ichComHeader.EntryPointToken;
+ obBuffer << m_ichComHeader.Resources.VirtualAddress;
+ obBuffer << m_ichComHeader.Resources.Size;
+ obBuffer << m_ichComHeader.StrongNameSignature.VirtualAddress;
+ obBuffer << m_ichComHeader.StrongNameSignature.Size;
+ obBuffer << m_ichComHeader.CodeManagerTable.VirtualAddress;
+ obBuffer << m_ichComHeader.CodeManagerTable.Size;
+ obBuffer << m_ichComHeader.VTableFixups.VirtualAddress;
+ obBuffer << m_ichComHeader.VTableFixups.Size;
+ obBuffer << m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
+ obBuffer << m_ichComHeader.ExportAddressTableJumps.Size;
+ obBuffer << m_ichComHeader.ManagedNativeHeader.VirtualAddress;
+ obBuffer << m_ichComHeader.ManagedNativeHeader.Size;
+ }
+
+ /**
+ * @return Size in bytes.
+ **/
+ unsigned int ComHeaderDirectory::size() const
+ {
+ return PELIB_IMAGE_COR20_HEADER::size();
+ }
+
+ /**
+ * @param strFilename Name of the file.
+ * @param dwOffset File offset the COM+ descriptor will be written to.
+ **/
+ int ComHeaderDirectory::write(const std::string& strFilename, unsigned int dwOffset) const
+ {
+ std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
+
+ if (!ofFile)
+ {
+ ofFile.clear();
+ ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
+ }
+ else
+ {
+ ofFile.close();
+ ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
+ }
+
+ if (!ofFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ ofFile.seekp(dwOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBuffer;
+ rebuild(vBuffer);
+
+ ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
+
+ ofFile.close();
+
+ return NO_ERROR;
+ }
+
+ /**
+ * @return SizeOfHeader value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getSizeOfHeader() const
+ {
+ return m_ichComHeader.cb;
+ }
+
+ /**
+ * @return MajorRuntimeVersion value of the current COM+ descriptor.
+ **/
+ word ComHeaderDirectory::getMajorRuntimeVersion() const
+ {
+ return m_ichComHeader.MajorRuntimeVersion;
+ }
+
+ /**
+ * @return MinorRuntimeVersion value of the current COM+ descriptor.
+ **/
+ word ComHeaderDirectory::getMinorRuntimeVersion() const
+ {
+ return m_ichComHeader.MinorRuntimeVersion;
+ }
+
+ /**
+ * @return MetaData (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getMetaDataVa() const
+ {
+ return m_ichComHeader.MetaData.VirtualAddress;
+ }
+
+ /**
+ * @return MetaData (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getMetaDataSize() const
+ {
+ return m_ichComHeader.MetaData.Size;
+ }
+
+ /**
+ * @return Flags value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getFlags() const
+ {
+ return m_ichComHeader.Flags;
+ }
+
+ /**
+ * @return EntryPointToken value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getEntryPointToken() const
+ {
+ return m_ichComHeader.EntryPointToken;
+ }
+
+ /**
+ * @return Resources (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getResourcesVa() const
+ {
+ return m_ichComHeader.Resources.VirtualAddress;
+ }
+
+ /**
+ * @return Resources (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getResourcesSize()
+ {
+ return m_ichComHeader.Resources.Size;
+ }
+
+ /**
+ * @return StrongNameSignature (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getStrongNameSignatureVa() const
+ {
+ return m_ichComHeader.StrongNameSignature.VirtualAddress;
+ }
+
+ /**
+ * @return StrongNameSignature (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getStrongNameSignagureSize() const
+ {
+ return m_ichComHeader.StrongNameSignature.Size;
+ }
+
+ /**
+ * @return CodeManagerTable (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getCodeManagerTableVa() const
+ {
+ return m_ichComHeader.CodeManagerTable.VirtualAddress;
+ }
+
+ /**
+ * @return CodeManagerTable (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getCodeManagerTableSize() const
+ {
+ return m_ichComHeader.CodeManagerTable.Size;
+ }
+
+ /**
+ * @return VTableFixups (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getVTableFixupsVa() const
+ {
+ return m_ichComHeader.VTableFixups.VirtualAddress;
+ }
+
+ /**
+ * @return VTableFixups (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getVTableFixupsSize() const
+ {
+ return m_ichComHeader.VTableFixups.Size;
+ }
+
+ /**
+ * @return ExportAddressTableJumps (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getExportAddressTableJumpsVa() const
+ {
+ return m_ichComHeader.ExportAddressTableJumps.VirtualAddress;
+ }
+
+ /**
+ * @return ExportAddressTableJumps (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getExportAddressTableJumpsSize() const
+ {
+ return m_ichComHeader.ExportAddressTableJumps.Size;
+ }
+
+ /**
+ * @return ManagedNativeHeader (Virtual Address) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getManagedNativeHeaderVa() const
+ {
+ return m_ichComHeader.ManagedNativeHeader.VirtualAddress;
+ }
+
+ /**
+ * @return ManagedNativeHeader (Size) value of the current COM+ descriptor.
+ **/
+ dword ComHeaderDirectory::getManagedNativeHeaderSize() const
+ {
+ return m_ichComHeader.ManagedNativeHeader.Size;
+ }
+
+ /**
+ * @param dwValue New value for the current SizeOfHeader (cb) value.
+ **/
+ void ComHeaderDirectory::setSizeOfHeader(dword dwValue)
+ {
+ m_ichComHeader.cb = dwValue;
+ }
+
+ /**
+ * @param wValue New value for the current MajorRuntimeVersion value.
+ **/
+ void ComHeaderDirectory::setMajorRuntimeVersion(word wValue)
+ {
+ m_ichComHeader.MajorRuntimeVersion = wValue;
+ }
+
+ /**
+ * @param wValue New value for the current MinorRuntimeVersion value.
+ **/
+ void ComHeaderDirectory::setMinorRuntimeVersion(word wValue)
+ {
+ m_ichComHeader.MinorRuntimeVersion = wValue;
+ }
+
+ /**
+ * @param dwValue New value for the current MetaData (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setMetaDataVa(dword dwValue)
+ {
+ m_ichComHeader.MetaData.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current MetaData (Size) value.
+ **/
+ void ComHeaderDirectory::setMetaDataSize(dword dwValue)
+ {
+ m_ichComHeader.MetaData.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current Flags value.
+ **/
+ void ComHeaderDirectory::setFlags(dword dwValue)
+ {
+ m_ichComHeader.Flags = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current EntryPointToken value.
+ **/
+ void ComHeaderDirectory::setEntryPointToken(dword dwValue)
+ {
+ m_ichComHeader.EntryPointToken = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current Resources (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setResourcesVa(dword dwValue)
+ {
+ m_ichComHeader.Resources.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current Resources (Size) value.
+ **/
+ void ComHeaderDirectory::setResourcesSize(dword dwValue)
+ {
+ m_ichComHeader.Resources.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current StrongNameSignature (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setStrongNameSignatureVa(dword dwValue)
+ {
+ m_ichComHeader.StrongNameSignature.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current StrongNameSignature (Size) value.
+ **/
+ void ComHeaderDirectory::setStrongNameSignagureSize(dword dwValue)
+ {
+ m_ichComHeader.StrongNameSignature.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current CodeManagerTable (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setCodeManagerTableVa(dword dwValue)
+ {
+ m_ichComHeader.CodeManagerTable.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current CodeManagerTable (Size) value.
+ **/
+ void ComHeaderDirectory::setCodeManagerTableSize(dword dwValue)
+ {
+ m_ichComHeader.CodeManagerTable.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current VTableFixups (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setVTableFixupsVa(dword dwValue)
+ {
+ m_ichComHeader.VTableFixups.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current VTableFixups (Size) value.
+ **/
+ void ComHeaderDirectory::setVTableFixupsSize(dword dwValue)
+ {
+ m_ichComHeader.VTableFixups.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current ExportAddressTableJumps (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setExportAddressTableJumpsVa(dword dwValue)
+ {
+ m_ichComHeader.ExportAddressTableJumps.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current ExportAddressTableJumps (Size) value.
+ **/
+ void ComHeaderDirectory::setExportAddressTableJumpsSize(dword dwValue)
+ {
+ m_ichComHeader.ExportAddressTableJumps.Size = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current ManagedNativeHeader (VirtualAddress) value.
+ **/
+ void ComHeaderDirectory::setManagedNativeHeaderVa(dword dwValue)
+ {
+ m_ichComHeader.ManagedNativeHeader.VirtualAddress = dwValue;
+ }
+
+ /**
+ * @param dwValue New value for the current ManagedNativeHeader (Size) value.
+ **/
+ void ComHeaderDirectory::setManagedNativeHeaderSize(dword dwValue)
+ {
+ m_ichComHeader.ManagedNativeHeader.Size = dwValue;
+ }
+
+}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h new file mode 100755 index 0000000000..915813c1cc --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/ComHeaderDirectory.h @@ -0,0 +1,120 @@ +/*
+* ComHeaderDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef COMHEADERDIRECTORY_H
+#define COMHEADERDIRECTORY_H
+
+namespace PeLib
+{
+ /// Class that handles the COM+ descriptor directory.
+ /**
+ * This class handles the COM+ Descriptor directory which was added to PE files
+ * which work with the .NET runtime modules.
+ **/
+ class ComHeaderDirectory
+ {
+ private:
+ PELIB_IMAGE_COR20_HEADER m_ichComHeader; ///< The COM+ descriptor.
+
+ void read(InputBuffer& inputbuffer);
+
+ public:
+ /// Read a file's COM+ runtime descriptor directory.
+ int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
+ int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
+ /// Rebuild the COM+ descriptor.
+ void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
+ /// Returns the size of the current COM+ descriptor.
+ unsigned int size() const; // EXPORT
+ /// Writes the current COM+ descriptor directory to a file.
+ int write(const std::string& strFilename, unsigned int dwOffset) const; // EXPORT
+
+ /// Get the COM+ descriptor's SizeOfHeader (cb) value.
+ dword getSizeOfHeader() const; // EXPORT
+ /// Get the COM+ descriptor's MajorRuntimeVersion value.
+ word getMajorRuntimeVersion() const; // EXPORT
+ /// Get the COM+ descriptor's MinorRuntimeVersion value.
+ word getMinorRuntimeVersion() const; // EXPORT
+ /// Get the COM+ descriptor's MetaData (Virtual Address) value.
+ dword getMetaDataVa() const; // EXPORT
+ /// Get the COM+ descriptor's MetaData (Size) value.
+ dword getMetaDataSize() const; // EXPORT
+ /// Get the COM+ descriptor's Flags value.
+ dword getFlags() const; // EXPORT
+ /// Get the COM+ descriptor's EntryPointToken value.
+ dword getEntryPointToken() const; // EXPORT
+ /// Get the COM+ descriptor's Resources (Virtual Address) value.
+ dword getResourcesVa() const; // EXPORT
+ /// Get the COM+ descriptor's Resources (Size) value.
+ dword getResourcesSize(); // EXPORT
+ /// Get the COM+ descriptor's StrongNameSignature (Virtual Address) value.
+ dword getStrongNameSignatureVa() const; // EXPORT
+ /// Get the COM+ descriptor's StrongNameSignature (Size) value.
+ dword getStrongNameSignagureSize() const; // EXPORT
+ /// Get the COM+ descriptor's CodeManagerTable (Virtual Address) value.
+ dword getCodeManagerTableVa() const; // EXPORT
+ /// Get the COM+ descriptor's CodeManagerTable (Size) value.
+ dword getCodeManagerTableSize() const; // EXPORT
+ /// Get the COM+ descriptor's VTableFixup (Virtual Address) value.
+ dword getVTableFixupsVa() const; // EXPORT
+ /// Get the COM+ descriptor's VTableFixup (Size) value.
+ dword getVTableFixupsSize() const; // EXPORT
+ /// Get the COM+ descriptor's ExportAddressTable (Virtual Address) value.
+ dword getExportAddressTableJumpsVa() const; // EXPORT
+ /// Get the COM+ descriptor's ExportAddressTable (Size) value.
+ dword getExportAddressTableJumpsSize() const; // EXPORT
+ /// Get the COM+ descriptor's ManagedNativeHeader (Virtual Address) value.
+ dword getManagedNativeHeaderVa() const; // EXPORT
+ /// Get the COM+ descriptor's ManagedNativeHeader (Size) value.
+ dword getManagedNativeHeaderSize() const; // EXPORT
+
+ /// Change the COM+ descriptor's SizeOfHeader (cb) value.
+ void setSizeOfHeader(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's MajorRuntimeVersion value.
+ void setMajorRuntimeVersion(word wValue); // EXPORT
+ /// Change the COM+ descriptor's MinorRuntimeVersion value.
+ void setMinorRuntimeVersion(word wValue); // EXPORT
+ /// Change the COM+ descriptor's MetaData (VirtualAddress) value.
+ void setMetaDataVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's MetaData (Size) value.
+ void setMetaDataSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's Flags value.
+ void setFlags(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's EntryPointToken value.
+ void setEntryPointToken(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's Resources (VirtualAddress) value.
+ void setResourcesVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's Resources (Size) value.
+ void setResourcesSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's StrongNameSignatureVa (VirtualAddress) value.
+ void setStrongNameSignatureVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's StrongNameSignatureVa (Size) value.
+ void setStrongNameSignagureSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's CodeManagerTable (VirtualAddress) value.
+ void setCodeManagerTableVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's CodeManagerTable (Size) value.
+ void setCodeManagerTableSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's VTableFixups (VirtualAddress) value.
+ void setVTableFixupsVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's VTableFixups (Size) value.
+ void setVTableFixupsSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's ExportAddressTableJumps (VirtualAddress) value.
+ void setExportAddressTableJumpsVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's ExportAddressTableJumps (Size) value.
+ void setExportAddressTableJumpsSize(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's ManagedNativeHeader (VirtualAddress) value.
+ void setManagedNativeHeaderVa(dword dwValue); // EXPORT
+ /// Change the COM+ descriptor's ManagedNativeHeader (Size) value.
+ void setManagedNativeHeaderSize(dword dwValue); // EXPORT
+ };
+}
+#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp new file mode 100755 index 0000000000..eb3d5c5600 --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.cpp @@ -0,0 +1,383 @@ +/*
+* DebugDirectory.cpp - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#include "PeLibInc.h"
+#include "DebugDirectory.h"
+
+namespace PeLib
+{
+ void DebugDirectory::clear()
+ {
+ m_vDebugInfo.clear();
+ }
+
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> DebugDirectory::read(InputBuffer& ibBuffer, unsigned int uiSize)
+ {
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo;
+
+ PELIB_IMG_DEBUG_DIRECTORY iddCurr;
+
+ for (unsigned int i=0;i<uiSize/PELIB_IMAGE_DEBUG_DIRECTORY::size();i++)
+ {
+
+ ibBuffer >> iddCurr.idd.Characteristics;
+ ibBuffer >> iddCurr.idd.TimeDateStamp;
+ ibBuffer >> iddCurr.idd.MajorVersion;
+ ibBuffer >> iddCurr.idd.MinorVersion;
+ ibBuffer >> iddCurr.idd.Type;
+ ibBuffer >> iddCurr.idd.SizeOfData;
+ ibBuffer >> iddCurr.idd.AddressOfRawData;
+ ibBuffer >> iddCurr.idd.PointerToRawData;
+
+ currDebugInfo.push_back(iddCurr);
+ }
+
+ return currDebugInfo;
+ }
+
+ int DebugDirectory::read(unsigned char* buffer, unsigned int buffersize)
+ {
+ // XXX: Note, debug data is not read at all. This might or might not change
+ // in the future.
+
+ std::vector<byte> vDebugDirectory(buffer, buffer + buffersize);
+
+ InputBuffer ibBuffer(vDebugDirectory);
+
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, buffersize);
+
+ std::swap(currDebugInfo, m_vDebugInfo);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * @param strFilename Name of the file which will be read.
+ * @param uiOffset File offset of the Debug directory.
+ * @param uiSize Size of the Debug directory.
+ **/
+ int DebugDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize)
+ {
+ std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
+ unsigned int ulFileSize = fileSize(ifFile);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ if (ulFileSize < uiOffset + uiSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(uiOffset, std::ios::beg);
+
+ std::vector<byte> vDebugDirectory(uiSize);
+ ifFile.read(reinterpret_cast<char*>(&vDebugDirectory[0]), uiSize);
+
+ InputBuffer ibBuffer(vDebugDirectory);
+
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> currDebugInfo = read(ibBuffer, uiSize);
+
+ for (unsigned int i=0;i<currDebugInfo.size();i++)
+ {
+ ifFile.seekg(currDebugInfo[i].idd.PointerToRawData, std::ios::beg);
+ currDebugInfo[i].data.resize(currDebugInfo[i].idd.SizeOfData);
+ ifFile.read(reinterpret_cast<char*>(&currDebugInfo[i].data[0]), currDebugInfo[i].idd.SizeOfData);
+ if (!ifFile) return ERROR_INVALID_FILE;
+ }
+
+ std::swap(currDebugInfo, m_vDebugInfo);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Rebuilds the current debug directory.
+ * @param vBuffer Buffer where the rebuilt directory is stored.
+ **/
+ void DebugDirectory::rebuild(std::vector<byte>& vBuffer) const
+ {
+ OutputBuffer obBuffer(vBuffer);
+
+ for (unsigned int i=0;i<m_vDebugInfo.size();i++)
+ {
+ obBuffer << m_vDebugInfo[i].idd.Characteristics;
+ obBuffer << m_vDebugInfo[i].idd.TimeDateStamp;
+ obBuffer << m_vDebugInfo[i].idd.MajorVersion;
+ obBuffer << m_vDebugInfo[i].idd.MinorVersion;
+ obBuffer << m_vDebugInfo[i].idd.Type;
+ obBuffer << m_vDebugInfo[i].idd.SizeOfData;
+ obBuffer << m_vDebugInfo[i].idd.AddressOfRawData;
+ obBuffer << m_vDebugInfo[i].idd.PointerToRawData;
+ }
+ }
+
+ /**
+ * @return Size of the debug directory.
+ **/
+ unsigned int DebugDirectory::size() const
+ {
+ return static_cast<unsigned int>(m_vDebugInfo.size()) * PELIB_IMAGE_DEBUG_DIRECTORY::size();
+ }
+
+ /**
+ * @param strFilename Name of the file which will be written.
+ * @param uiOffset File offset where the debug directory will be stored.
+ **/
+ int DebugDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
+ {
+ std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
+
+ if (!ofFile)
+ {
+ ofFile.clear();
+ ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
+ }
+ else
+ {
+ ofFile.close();
+ ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
+ }
+
+ if (!ofFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ ofFile.seekp(uiOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBuffer;
+ rebuild(vBuffer);
+
+ ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
+
+ ofFile.close();
+
+ return NO_ERROR;
+ }
+
+ /**
+ * @return Number of debug structures in the current Debug directory.
+ **/
+ unsigned int DebugDirectory::calcNumberOfEntries() const
+ {
+ return static_cast<unsigned int>(m_vDebugInfo.size());
+ }
+
+ /**
+ * Adds a new debug structure to the debug directory. The initial values of all members of the structure
+ * are undefined.
+ **/
+ void DebugDirectory::addEntry()
+ {
+ PELIB_IMG_DEBUG_DIRECTORY p;
+ m_vDebugInfo.push_back(p);
+ }
+
+ /**
+ * Removes a debug structure from the current debug directory. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ **/
+ void DebugDirectory::removeEntry(unsigned int uiIndex)
+ {
+ m_vDebugInfo.erase(m_vDebugInfo.begin() + uiIndex);
+ }
+
+ /**
+ * Returns the Characteristics value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return Characteristics value of the debug structure.
+ **/
+ dword DebugDirectory::getCharacteristics(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.Characteristics;
+ }
+
+ /**
+ * Returns the TimeDateStamp value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return TimeDateStamp value of the debug structure.
+ **/
+ dword DebugDirectory::getTimeDateStamp(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.TimeDateStamp;
+ }
+
+ /**
+ * Returns the MajorVersion value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return MajorVersion value of the debug structure.
+ **/
+ word DebugDirectory::getMajorVersion(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.MajorVersion;
+ }
+
+ /**
+ * Returns the MinorVersion value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return MinorVersion value of the debug structure.
+ **/
+ word DebugDirectory::getMinorVersion(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.MinorVersion;
+ }
+
+ /**
+ * Returns the Type value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return Type value of the debug structure.
+ **/
+ dword DebugDirectory::getType(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.Type;
+ }
+
+ /**
+ * Returns the SizeOfData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return SizeOfData value of the debug structure.
+ **/
+ dword DebugDirectory::getSizeOfData(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.SizeOfData;
+ }
+
+ /**
+ * Returns the AddressOfRawData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return AddressOfRawData value of the debug structure.
+ **/
+ dword DebugDirectory::getAddressOfRawData(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.AddressOfRawData;
+ }
+
+ /**
+ * Returns the PointerToRawData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @return PointerToRawData value of the debug structure.
+ **/
+ dword DebugDirectory::getPointerToRawData(unsigned int uiIndex) const
+ {
+ return m_vDebugInfo[uiIndex].idd.PointerToRawData;
+ }
+
+ std::vector<byte> DebugDirectory::getData(unsigned int index) const
+ {
+ return m_vDebugInfo[index].data;
+ }
+
+ /**
+ * Changes the Characteristics value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the Characteristics value of the debug structure.
+ **/
+ void DebugDirectory::setCharacteristics(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.Characteristics = dwValue;
+ }
+
+ /**
+ * Changes the TimeDateStamp value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the TimeDateStamp value of the debug structure.
+ **/
+ void DebugDirectory::setTimeDateStamp(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.TimeDateStamp = dwValue;
+ }
+
+ /**
+ * Changes the MajorVersion value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param wValue New value of the MajorVersion value of the debug structure.
+ **/
+ void DebugDirectory::setMajorVersion(unsigned int uiIndex, word wValue)
+ {
+ m_vDebugInfo[uiIndex].idd.MajorVersion = wValue;
+ }
+
+ /**
+ * Changes the MinorVersion value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param wValue New value of the MinorVersion value of the debug structure.
+ **/
+ void DebugDirectory::setMinorVersion(unsigned int uiIndex, word wValue)
+ {
+ m_vDebugInfo[uiIndex].idd.MinorVersion = wValue;
+ }
+
+ /**
+ * Changes the Type value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the Type value of the debug structure.
+ **/
+ void DebugDirectory::setType(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.Type = dwValue;
+ }
+
+ /**
+ * Changes the SizeOfData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the SizeOfData value of the debug structure.
+ **/
+ void DebugDirectory::setSizeOfData(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.SizeOfData = dwValue;
+ }
+
+ /**
+ * Changes the AddressOfRawData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the AddressOfRawData value of the debug structure.
+ **/
+ void DebugDirectory::setAddressOfRawData(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.AddressOfRawData = dwValue;
+ }
+
+ /**
+ * Changes the PointerToRawData value of a debug structure. If an invalid structure is specified
+ * by the parameter uiIndex the result will be undefined behaviour.
+ * @param uiIndex Identifies the debug structure.
+ * @param dwValue New value of the PointerToRawData value of the debug structure.
+ **/
+ void DebugDirectory::setPointerToRawData(unsigned int uiIndex, dword dwValue)
+ {
+ m_vDebugInfo[uiIndex].idd.PointerToRawData = dwValue;
+ }
+
+ void DebugDirectory::setData(unsigned int index, const std::vector<byte>& data)
+ {
+ m_vDebugInfo[index].data = data;
+ }
+}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h new file mode 100755 index 0000000000..0ffda38815 --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/DebugDirectory.h @@ -0,0 +1,84 @@ +/*
+* DebugDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef DEBUGDIRECTORY_H
+#define DEBUGDIRECTORY_H
+
+namespace PeLib
+{
+ /// Class that handles the Debug directory.
+ class DebugDirectory
+ {
+ private:
+ /// Stores the various DebugDirectory structures.
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> m_vDebugInfo;
+
+ std::vector<PELIB_IMG_DEBUG_DIRECTORY> read(InputBuffer& ibBuffer, unsigned int uiSize);
+
+ public:
+ void clear(); // EXPORT
+ /// Reads the Debug directory from a file.
+ int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize); // EXPORT
+ int read(unsigned char* buffer, unsigned int buffersize);
+ /// Rebuilds the current Debug directory.
+ void rebuild(std::vector<byte>& obBuffer) const; // EXPORT
+ /// Returns the size the current Debug directory needs after rebuilding.
+ unsigned int size() const;
+ /// Writes the current Debug directory back to a file.
+ int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
+
+ /// Returns the number of DebugDirectory image structures in the current DebugDirectory.
+ unsigned int calcNumberOfEntries() const; // EXPORT
+
+ /// Adds a new debug structure.
+ void addEntry(); // EXPORT
+ /// Removes a debug structure.
+ void removeEntry(unsigned int uiIndex); // EXPORT
+
+ /// Returns the Characteristics value of a debug structure.
+ dword getCharacteristics(unsigned int uiIndex) const; // EXPORT
+ /// Returns the TimeDateStamp value of a debug structure.
+ dword getTimeDateStamp(unsigned int uiIndex) const; // EXPORT
+ /// Returns the MajorVersion value of a debug structure.
+ word getMajorVersion(unsigned int uiIndex) const; // EXPORT
+ /// Returns the MinorVersion value of a debug structure.
+ word getMinorVersion(unsigned int uiIndex) const; // EXPORT
+ /// Returns the Type value of a debug structure.
+ dword getType(unsigned int uiIndex) const; // EXPORT
+ /// Returns the SizeOfData value of a debug structure.
+ dword getSizeOfData(unsigned int uiIndex) const; // EXPORT
+ /// Returns the AddressOfRawData value of a debug structure.
+ dword getAddressOfRawData(unsigned int uiIndex) const; // EXPORT
+ /// Returns the PointerToRawData value of a debug structure.
+ dword getPointerToRawData(unsigned int uiIndex) const; // EXPORT
+ std::vector<byte> getData(unsigned int index) const; // EXPORT
+
+ /// Sets the Characteristics value of a debug structure.
+ void setCharacteristics(unsigned int uiIndex, dword dwValue); // EXPORT
+ /// Sets the TimeDateStamp value of a debug structure.
+ void setTimeDateStamp(unsigned int uiIndex, dword dwValue); // EXPORT
+ /// Sets the MajorVersion value of a debug structure.
+ void setMajorVersion(unsigned int uiIndex, word wValue); // EXPORT
+ /// Sets the MinorVersion value of a debug structure.
+ void setMinorVersion(unsigned int uiIndex, word wValue); // EXPORT
+ /// Sets the Type value of a debug structure.
+ void setType(unsigned int uiIndex, dword dwValue); // EXPORT
+ /// Sets the SizeOfData value of a debug structure.
+ void setSizeOfData(unsigned int uiIndex, dword dwValue); // EXPORT
+ /// Sets the AddressOfRawData value of a debug structure.
+ void setAddressOfRawData(unsigned int uiIndex, dword dwValue); // EXPORT
+ /// Sets the PointerToRawData value of a debug structure.
+ void setPointerToRawData(unsigned int uiIndex, dword dwValue); // EXPORT
+ void setData(unsigned int index, const std::vector<byte>& data); // EXPORT
+ };
+}
+#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp new file mode 100755 index 0000000000..aa9c28a50f --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.cpp @@ -0,0 +1,692 @@ +/*
+* ExportDirectory.cpp - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+//#ifdef false
+
+#include "PeLibInc.h"
+#include "ExportDirectory.h"
+
+namespace PeLib
+{
+ /**
+ * @param strFuncname Name of the function.
+ * @param dwFuncAddr RVA of the function.
+ **/
+ void ExportDirectory::addFunction(const std::string& strFuncname, dword dwFuncAddr)
+ {
+ PELIB_EXP_FUNC_INFORMATION efiCurr;
+ efiCurr.funcname = strFuncname;
+ efiCurr.addroffunc = dwFuncAddr;
+ m_ied.functions.push_back(efiCurr);
+ }
+
+ void ExportDirectory::removeFunction(unsigned int index)
+ {
+ m_ied.functions.erase(m_ied.functions.begin() + index);
+ }
+
+ void ExportDirectory::clear()
+ {
+ m_ied.functions.clear();
+ }
+
+ unsigned int ExportDirectory::calcNumberOfFunctions() const
+ {
+ return static_cast<unsigned int>(m_ied.functions.size());
+ }
+
+ /**
+ * Identifies an exported function through it's name.
+ * @param strFunctionName Name of the function
+ * @return Number which identifies the functions.
+ **/
+ int ExportDirectory::getFunctionIndex(const std::string& strFunctionName) const
+ {
+ std::vector<PELIB_EXP_FUNC_INFORMATION>::const_iterator Iter = std::find_if(m_ied.functions.begin(), m_ied.functions.end(), std::bind2nd(std::mem_fun_ref(&PELIB_EXP_FUNC_INFORMATION::equal), strFunctionName));
+
+ if (Iter == m_ied.functions.end())
+ {
+// throw Exceptions::InvalidName(ExportDirectoryId, __LINE__);
+ return -1;
+ }
+
+ return static_cast<int>(std::distance(m_ied.functions.begin(), Iter));
+ }
+
+ /**
+ * @param strFilename Name of the file.
+ * @param uiOffset File offset of the export directory.
+ * @param uiSize Size of the export directory.
+ * @param pehHeader A valid PE header which is necessary because some RVA calculations need to be done.
+ * \todo: Proper use of InputBuffer
+ **/
+ int ExportDirectory::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader)
+ {
+ std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ unsigned int filesize = fileSize(ifFile);
+
+ if (filesize < uiOffset + uiSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(uiOffset, std::ios::beg);
+
+ PELIB_IMAGE_EXP_DIRECTORY iedCurr;
+
+ std::vector<unsigned char> vExportdirectory(uiSize);
+ ifFile.read(reinterpret_cast<char*>(&vExportdirectory[0]), uiSize);
+
+ InputBuffer inpBuffer(vExportdirectory);
+
+ inpBuffer >> iedCurr.ied.Characteristics;
+ inpBuffer >> iedCurr.ied.TimeDateStamp;
+ inpBuffer >> iedCurr.ied.MajorVersion;
+ inpBuffer >> iedCurr.ied.MinorVersion;
+ inpBuffer >> iedCurr.ied.Name;
+ inpBuffer >> iedCurr.ied.Base;
+ inpBuffer >> iedCurr.ied.NumberOfFunctions;
+ inpBuffer >> iedCurr.ied.NumberOfNames;
+ inpBuffer >> iedCurr.ied.AddressOfFunctions;
+ inpBuffer >> iedCurr.ied.AddressOfNames;
+ inpBuffer >> iedCurr.ied.AddressOfNameOrdinals;
+
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.ied.Name);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: Files might be > 4 GB
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.Name));
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+
+ char c = 0;
+ std::string strFname = "";
+ do
+ {
+ ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
+ if (!ifFile) return ERROR_INVALID_FILE;
+ if (c) strFname += c;
+ }
+ while (c != 0);
+ iedCurr.name = strFname;
+
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: File might be > 4 GB
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions));
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+
+ PELIB_EXP_FUNC_INFORMATION efiCurr;
+ efiCurr.ordinal = 0; efiCurr.addroffunc = 0; efiCurr.addrofname = 0;
+
+ for (unsigned int i=0;i<iedCurr.ied.NumberOfFunctions;i++)
+ {
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfFunctions) + i*sizeof(efiCurr.addroffunc);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: File might be > 4GB
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfFunctions)) + i*sizeof(efiCurr.addroffunc);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+
+ ifFile.read(reinterpret_cast<char*>(&efiCurr.addroffunc), sizeof(efiCurr.addroffunc));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ efiCurr.ordinal = i;
+ iedCurr.functions.push_back(efiCurr);
+ }
+
+ for (unsigned int i=0;i<iedCurr.ied.NumberOfNames;i++)
+ {
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals) + i*sizeof(efiCurr.ordinal);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: File might be > 4 GB
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNameOrdinals)) + i*sizeof(efiCurr.ordinal);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+
+ word ordinal;
+ ifFile.read(reinterpret_cast<char*>(&ordinal), sizeof(ordinal));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ iedCurr.functions[ordinal].ordinal = ordinal;
+
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.ied.AddressOfNames) + i*sizeof(efiCurr.addrofname);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: File might be > 4 GB.
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.ied.AddressOfNames)) + i*sizeof(efiCurr.addrofname);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+
+ ifFile.read(reinterpret_cast<char*>(&iedCurr.functions[ordinal].addrofname), sizeof(iedCurr.functions[ordinal].addrofname));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ if (const PeHeader32* p32 = dynamic_cast<const PeHeader32*>(&pehHeader))
+ {
+ unsigned int offset = p32->rvaToOffset(iedCurr.functions[ordinal].addrofname);
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(offset, std::ios::beg);
+ }
+ else if (const PeHeader64* p64 = dynamic_cast<const PeHeader64*>(&pehHeader))
+ {
+ // XXX: File might be > 4 GB.
+ unsigned int offset = static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname));
+
+ if (offset >= filesize)
+ return ERROR_INVALID_FILE;
+
+ ifFile.seekg(static_cast<unsigned int>(p64->rvaToOffset(iedCurr.functions[ordinal].addrofname)), std::ios::beg);
+ }
+
+ char c = 0;
+ std::string strFname = "";
+ do
+ {
+ ifFile.read(reinterpret_cast<char*>(&c), sizeof(c));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ if (c) strFname += c;
+ }
+ while (c != 0);
+
+ iedCurr.functions[ordinal].funcname = strFname;
+ }
+
+ std::swap(m_ied, iedCurr);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * @param vBuffer Buffer where the rebuilt export directory is written to.
+ * @param dwRva RVA of the export directory.
+ * \todo fValid flag
+ **/
+ void ExportDirectory::rebuild(std::vector<byte>& vBuffer, dword dwRva) const
+ {
+ unsigned int uiSizeDirectory = sizeof(PELIB_IMAGE_EXPORT_DIRECTORY);
+
+ unsigned int uiSizeNames = 0;
+ unsigned int uiSizeAddrFuncs = 0;
+ unsigned int uiSizeAddrNames = 0;
+ unsigned int uiSizeOrdinals = 0;
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ uiSizeNames += (m_ied.functions[i].funcname.empty()) ? 0 : static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
+ uiSizeAddrFuncs += sizeof(m_ied.functions[i].addroffunc);
+ uiSizeAddrNames += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].addrofname);
+ uiSizeOrdinals += (m_ied.functions[i].funcname.empty()) ? 0 : sizeof(m_ied.functions[i].ordinal);
+ }
+
+ unsigned int uiFilenameSize = static_cast<unsigned int>(m_ied.name.size()) + 1;
+
+ OutputBuffer obBuffer(vBuffer);
+
+ obBuffer << m_ied.ied.Characteristics;
+ obBuffer << m_ied.ied.TimeDateStamp;
+ obBuffer << m_ied.ied.MajorVersion;
+ obBuffer << m_ied.ied.MinorVersion;
+ obBuffer << dwRva + uiSizeDirectory;
+ obBuffer << m_ied.ied.Base;
+ obBuffer << static_cast<unsigned int>(m_ied.functions.size());
+
+ // TODO: Not correct but sufficient for now. (Update: I forgot what this comment refers to, but I'll leave it in)
+ obBuffer << static_cast<unsigned int>(m_ied.functions.size());
+ obBuffer << dwRva + uiSizeDirectory + uiFilenameSize;
+ obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs;
+ obBuffer << dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames;
+
+ obBuffer.add(m_ied.name.c_str(), static_cast<unsigned int>(m_ied.name.size())+1);
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ obBuffer << m_ied.functions[i].addroffunc;
+ }
+
+ unsigned int ulFuncCounter = dwRva + uiSizeDirectory + uiFilenameSize + uiSizeAddrFuncs + uiSizeAddrNames + uiSizeOrdinals;
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ if (!m_ied.functions[i].funcname.empty())
+ {
+ obBuffer << ulFuncCounter;
+ ulFuncCounter += static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1;
+ }
+ }
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ if (!m_ied.functions[i].funcname.empty())
+ {
+ obBuffer << m_ied.functions[i].ordinal;
+ }
+ }
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ if (m_ied.functions[i].funcname.empty() && m_ied.functions[i].addroffunc)
+ {
+ obBuffer << m_ied.functions[i].ordinal;
+ }
+ }
+
+ for (unsigned int i=0;i<m_ied.functions.size();i++)
+ {
+ if (!m_ied.functions[i].funcname.empty())
+ {
+ obBuffer.add(m_ied.functions[i].funcname.c_str(), static_cast<unsigned int>(m_ied.functions[i].funcname.size()) + 1);
+ }
+ }
+ }
+
+ /**
+ * @return Size of the current export directory.
+ **/
+ unsigned int ExportDirectory::size() const
+ {
+ return m_ied.size();
+ }
+
+ /**
+ * @param strFilename Name of the file.
+ * @param uiOffset File offset the export directory will be written to.
+ * @param uiRva RVA of the export directory.
+ * \todo Check if ofFile.write succeeded.
+ **/
+ int ExportDirectory::write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const
+ {
+ std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
+
+ if (!ofFile)
+ {
+ ofFile.clear();
+ ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
+ }
+ else
+ {
+ ofFile.close();
+ ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
+ }
+
+ if (!ofFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ ofFile.seekp(uiOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBuffer;
+ rebuild(vBuffer, uiRva);
+
+ ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
+
+ ofFile.close();
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Changes the filename according to the export directory.
+ * @param strFilename New filename.
+ **/
+ void ExportDirectory::setNameString(const std::string& strFilename)
+ {
+ m_ied.name = strFilename;
+ }
+
+ std::string ExportDirectory::getNameString() const
+ {
+ return m_ied.name;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @return The name of that function.
+ **/
+ std::string ExportDirectory::getFunctionName(dword dwIndex) const
+ {
+ return m_ied.functions[dwIndex].funcname;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @return The ordinal of that function.
+ **/
+ word ExportDirectory::getFunctionOrdinal(dword dwIndex) const
+ {
+ return m_ied.functions[dwIndex].ordinal;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @return The RVA of the name string of that function.
+ **/
+ dword ExportDirectory::getAddressOfName(dword dwIndex) const
+ {
+ return m_ied.functions[dwIndex].addrofname;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @return The RVA of that function.
+ **/
+ dword ExportDirectory::getAddressOfFunction(dword dwIndex) const
+ {
+ return m_ied.functions[dwIndex].addroffunc;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @param strName The name of that function.
+ **/
+ void ExportDirectory::setFunctionName(dword dwIndex, const std::string& strName)
+ {
+ m_ied.functions[dwIndex].funcname = strName;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @param wValue The ordinal of that function.
+ **/
+ void ExportDirectory::setFunctionOrdinal(dword dwIndex, word wValue)
+ {
+ m_ied.functions[dwIndex].ordinal = wValue;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @param dwValue The RVA of the name string of that function.
+ **/
+ void ExportDirectory::setAddressOfName(dword dwIndex, dword dwValue)
+ {
+ m_ied.functions[dwIndex].addrofname = dwValue;
+ }
+
+ /**
+ * @param dwIndex Number which identifies an exported function.
+ * @param dwValue The RVA of that function.
+ **/
+ void ExportDirectory::setAddressOfFunction(dword dwIndex, dword dwValue)
+ {
+ m_ied.functions[dwIndex].addroffunc = dwValue;
+ }
+
+ /**
+ * @return The ordinal base of the export directory.
+ **/
+ dword ExportDirectory::getBase() const
+ {
+ return m_ied.ied.Base;
+ }
+
+ /**
+ * @return The characteristics of the export directory.
+ **/
+ dword ExportDirectory::getCharacteristics() const
+ {
+ return m_ied.ied.Characteristics;
+ }
+
+ /**
+ * @return The time/date stamp of the export directory.
+ **/
+ dword ExportDirectory::getTimeDateStamp() const
+ {
+ return m_ied.ied.TimeDateStamp;
+ }
+
+ /**
+ * @return The MajorVersion of the export directory.
+ **/
+ word ExportDirectory::getMajorVersion() const
+ {
+ return m_ied.ied.MajorVersion;
+ }
+
+ /**
+ * @return The MinorVersion of the export directory.
+ **/
+ word ExportDirectory::getMinorVersion() const
+ {
+ return m_ied.ied.MinorVersion;
+ }
+
+ /**
+ * @return The RVA of the name of the file.
+ **/
+ dword ExportDirectory::getName() const
+ {
+ return m_ied.ied.Name;
+ }
+
+ /**
+ * @return The NumberOfFunctions of the export directory.
+ **/
+ dword ExportDirectory::getNumberOfFunctions() const
+ {
+ return m_ied.ied.NumberOfFunctions;
+ }
+
+ /**
+ * @return The NumberOfNames of the export directory.
+ **/
+ dword ExportDirectory::getNumberOfNames() const
+ {
+ return m_ied.ied.NumberOfNames;
+ }
+
+ /**
+ * @return The AddressOfFunctions of the export directory.
+ **/
+ dword ExportDirectory::getAddressOfFunctions() const
+ {
+ return m_ied.ied.AddressOfFunctions;
+ }
+
+ /**
+ * @return The AddressOfNames of the export directory.
+ **/
+ dword ExportDirectory::getAddressOfNames() const
+ {
+ return m_ied.ied.AddressOfNames;
+ }
+
+/* dword ExportDirectory::getNumberOfNameOrdinals() const
+ {
+ return static_cast<dword>(m_ied.functions.size());
+ }
+
+ dword ExportDirectory::getNumberOfAddressOfFunctionNames() const
+ {
+ return static_cast<dword>(m_ied.functions.size());
+ }
+
+ dword ExportDirectory::getNumberOfAddressOfFunctions() const
+ {
+ return static_cast<dword>(m_ied.functions.size());
+ }
+*/
+ /**
+ * @return The AddressOfNameOrdinals of the export directory.
+ **/
+ dword ExportDirectory::getAddressOfNameOrdinals() const
+ {
+ return m_ied.ied.AddressOfNameOrdinals;
+ }
+
+ /**
+ * @param dwValue The ordinal base of the export directory.
+ **/
+ void ExportDirectory::setBase(dword dwValue)
+ {
+ m_ied.ied.Base = dwValue;
+ }
+
+ /**
+ * @param dwValue The Characteristics of the export directory.
+ **/
+ void ExportDirectory::setCharacteristics(dword dwValue)
+ {
+ m_ied.ied.Characteristics = dwValue;
+ }
+
+ /**
+ * @param dwValue The TimeDateStamp of the export directory.
+ **/
+ void ExportDirectory::setTimeDateStamp(dword dwValue)
+ {
+ m_ied.ied.TimeDateStamp = dwValue;
+ }
+
+ /**
+ * @param wValue The MajorVersion of the export directory.
+ **/
+ void ExportDirectory::setMajorVersion(word wValue)
+ {
+ m_ied.ied.MajorVersion = wValue;
+ }
+
+ /**
+ * @param wValue The MinorVersion of the export directory.
+ **/
+ void ExportDirectory::setMinorVersion(word wValue)
+ {
+ m_ied.ied.MinorVersion = wValue;
+ }
+
+ /**
+ * @param dwValue The Name of the export directory.
+ **/
+ void ExportDirectory::setName(dword dwValue)
+ {
+ m_ied.ied.Name = dwValue;
+ }
+
+ /**
+ * @param dwValue The NumberOfFunctions of the export directory.
+ **/
+ void ExportDirectory::setNumberOfFunctions(dword dwValue)
+ {
+ m_ied.ied.NumberOfFunctions = dwValue;
+ }
+
+ /**
+ * @param dwValue The NumberOfNames of the export directory.
+ **/
+ void ExportDirectory::setNumberOfNames(dword dwValue)
+ {
+ m_ied.ied.NumberOfNames = dwValue;
+ }
+
+ /**
+ * @param dwValue The AddressOfFunctions of the export directory.
+ **/
+ void ExportDirectory::setAddressOfFunctions(dword dwValue)
+ {
+ m_ied.ied.AddressOfFunctions = dwValue;
+ }
+
+ /**
+ * @param dwValue The AddressOfNames of the export directory.
+ **/
+ void ExportDirectory::setAddressOfNames(dword dwValue)
+ {
+ m_ied.ied.AddressOfNames = dwValue;
+ }
+
+ void ExportDirectory::setAddressOfNameOrdinals(dword value)
+ {
+ m_ied.ied.AddressOfNameOrdinals = value;
+ }
+}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h new file mode 100755 index 0000000000..17a7e57020 --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/ExportDirectory.h @@ -0,0 +1,133 @@ +/*
+* ExportDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef EXPORTDIRECTORY_H
+#define EXPORTDIRECTORY_H
+#include "PeHeader.h"
+
+namespace PeLib
+{
+ /// Class that handles the export directory.
+ /**
+ * This class handles the export directory.
+ * \todo getNameString
+ **/
+// template<int bits>
+ class ExportDirectory
+ {
+ private:
+ /// Used to store all necessary information about a file's exported functions.
+ PELIB_IMAGE_EXP_DIRECTORY m_ied;
+
+ public:
+ /// Add another function to be exported.
+ void addFunction(const std::string& strFuncname, dword dwFuncAddr); // EXPORT
+ unsigned int calcNumberOfFunctions() const; // EXPORT
+ void clear(); // EXPORT
+ /// Identifies a function through it's name.
+ int getFunctionIndex(const std::string& strFunctionName) const; // EXPORT
+ /// Read a file's export directory.
+ int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeader& pehHeader); // EXPORT
+ /// Rebuild the current export directory.
+ void rebuild(std::vector<byte>& vBuffer, dword dwRva) const; // EXPORT
+ void removeFunction(unsigned int index); // EXPORT
+ /// Returns the size of the current export directory.
+ unsigned int size() const; // EXPORT
+ /// Writes the current export directory to a file.
+ int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva) const; // EXPORT
+
+ /// Changes the name of the file (according to the export directory).
+ void setNameString(const std::string& strFilename); // EXPORT
+ std::string getNameString() const; // EXPORT
+
+ /// Get the name of an exported function.
+ std::string getFunctionName(unsigned int index) const; // EXPORT
+ /// Get the ordinal of an exported function.
+ word getFunctionOrdinal(unsigned int index) const; // EXPORT
+ /// Get the address of the name of an exported function.
+ dword getAddressOfName(unsigned int index) const; // EXPORT
+ /// Get the address of an exported function.
+ dword getAddressOfFunction(unsigned int index) const; // EXPORT
+
+ /// Change the name of an exported function.
+ void setFunctionName(unsigned int index, const std::string& strName); // EXPORT
+ /// Change the ordinal of an exported function.
+ void setFunctionOrdinal(unsigned int index, word wValue); // EXPORT
+ /// Change the address of the name of an exported function.
+ void setAddressOfName(unsigned int index, dword dwValue); // EXPORT
+ /// Change the address of an exported function.
+ void setAddressOfFunction(unsigned int index, dword dwValue); // EXPORT
+
+ /*
+ word getFunctionOrdinal(std::string strFuncname) const;
+ dword getAddressOfName(std::string strFuncname) const;
+ dword getAddressOfFunction(std::string strFuncname) const;
+
+ void setFunctionOrdinal(std::string strFuncname, word wValue);
+ void setAddressOfName(std::string strFuncname, dword dwValue);
+ void setAddressOfFunction(std::string strFuncname, dword dwValue);
+ */
+
+ /// Return the Base value of the export directory.
+ dword getBase() const; // EXPORT
+ /// Return the Characteristics value of the export directory.
+ dword getCharacteristics() const; // EXPORT
+ /// Return the TimeDateStamp value of the export directory.
+ dword getTimeDateStamp() const; // EXPORT
+ /// Return the MajorVersion value of the export directory.
+ word getMajorVersion() const; // EXPORT
+ /// Return the MinorVersion value of the export directory.
+ word getMinorVersion() const; // EXPORT
+ /// Return the Name value of the export directory.
+ dword getName() const; // EXPORT
+ /// Return the NumberOfFunctions value of the export directory.
+ dword getNumberOfFunctions() const; // EXPORT
+ /// Return the NumberOfNames value of the export directory.
+ dword getNumberOfNames() const; // EXPORT
+ /// Return the AddressOfFunctions value of the export directory.
+ dword getAddressOfFunctions() const; // EXPORT
+ /// Return the AddressOfNames value of the export directory.
+ dword getAddressOfNames() const; // EXPORT
+ /// Returns the AddressOfNameOrdinals value.
+ dword getAddressOfNameOrdinals() const; // EXPORT
+
+/* /// Returns the number of NameOrdinals.
+ dword getNumberOfNameOrdinals() const; // EXPORT
+ /// Returns the number of AddressOfFunctionNames values.
+ dword getNumberOfAddressOfFunctionNames() const; // EXPORT
+ /// Returns the number of AddressOfFunction values.
+ dword getNumberOfAddressOfFunctions() const; // EXPORT
+*/
+ /// Set the Base value of the export directory.
+ void setBase(dword dwValue); // EXPORT
+ /// Set the Characteristics value of the export directory.
+ void setCharacteristics(dword dwValue); // EXPORT
+ /// Set the TimeDateStamp value of the export directory.
+ void setTimeDateStamp(dword dwValue); // EXPORT
+ /// Set the MajorVersion value of the export directory.
+ void setMajorVersion(word wValue); // EXPORT
+ /// Set the MinorVersion value of the export directory.
+ void setMinorVersion(word wValue); // EXPORT
+ /// Set the Name value of the export directory.
+ void setName(dword dwValue); // EXPORT
+ /// Set the NumberOfFunctions value of the export directory.
+ void setNumberOfFunctions(dword dwValue); // EXPORT
+ /// Set the NumberOfNames value of the export directory.
+ void setNumberOfNames(dword dwValue); // EXPORT
+ /// Set the AddressOfFunctions value of the export directory.
+ void setAddressOfFunctions(dword dwValue); // EXPORT
+ /// Set the AddressOfNames value of the export directory.
+ void setAddressOfNames(dword dwValue); // EXPORT
+ void setAddressOfNameOrdinals(dword value); // EXPORT
+ };
+}
+#endif
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp new file mode 100755 index 0000000000..36482fcbeb --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.cpp @@ -0,0 +1,179 @@ +/*
+* IatDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#include "IatDirectory.h"
+
+namespace PeLib
+{
+ int IatDirectory::read(InputBuffer& inputBuffer, unsigned int size)
+ {
+ dword dwAddr;
+
+ std::vector<dword> vIat;
+
+ for (unsigned int i=0;i<size/sizeof(dword);i++)
+ {
+ inputBuffer >> dwAddr;
+ vIat.push_back(dwAddr);
+ }
+
+ std::swap(vIat, m_vIat);
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Reads the Import Address table from a file.
+ * @param strFilename Name of the file.
+ * @param dwOffset File offset of the IAT (see #PeFile::PeHeader::getIDIatRVA).
+ * @param dwSize Size of the IAT (see #PeFile::PeHeader::getIDIatSize).
+ **/
+ int IatDirectory::read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize)
+ {
+ std::ifstream ifFile(strFilename.c_str(), std::ios::binary);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ if (fileSize(ifFile) < dwOffset + dwSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(dwOffset, std::ios::beg);
+
+ std::vector<byte> vBuffer(dwSize);
+ ifFile.read(reinterpret_cast<char*>(&vBuffer[0]), dwSize);
+
+ InputBuffer inpBuffer(vBuffer);
+ return read(inpBuffer, dwSize);
+ }
+
+ int IatDirectory::read(unsigned char* buffer, unsigned int buffersize)
+ {
+ std::vector<byte> vBuffer(buffer, buffer + buffersize);
+ InputBuffer inpBuffer(vBuffer);
+ return read(inpBuffer, buffersize);
+ }
+
+ /**
+ * Returns the number of fields in the IAT. This is equivalent to the number of
+ * imported functions.
+ * @return Number of fields in the IAT.
+ **/
+ unsigned int IatDirectory::calcNumberOfAddresses() const
+ {
+ return static_cast<unsigned int>(m_vIat.size());
+ }
+
+ /**
+ * Returns the dwValue of a field in the IAT.
+ * @param dwAddrnr Number identifying the field.
+ * @return dwValue of the field.
+ **/
+ dword IatDirectory::getAddress(unsigned int index) const
+ {
+ return m_vIat[index];
+ }
+
+ /**
+ * Updates the dwValue of a field in the IAT.
+ * @param dwAddrnr Number identifying the field.
+ * @param dwValue New dwValue of the field.
+ **/
+ void IatDirectory::setAddress(dword dwAddrnr, dword dwValue)
+ {
+ m_vIat[dwAddrnr] = dwValue;
+ }
+
+ /**
+ * Adds another field to the IAT.
+ * @param dwValue dwValue of the new field.
+ **/
+ void IatDirectory::addAddress(dword dwValue)
+ {
+ m_vIat.push_back(dwValue);
+ }
+
+ /**
+ * Removes an address from the IAT.
+ * @param dwAddrnr Number identifying the field.
+ **/
+ void IatDirectory::removeAddress(unsigned int index)
+ {
+ std::vector<dword>::iterator pos = m_vIat.begin() + index;
+ m_vIat.erase(pos);
+ }
+
+ /**
+ * Delete all entries from the IAT.
+ **/
+ void IatDirectory::clear()
+ {
+ m_vIat.clear();
+ }
+
+ /**
+ * Rebuilds the complete Import Address Table.
+ * @param vBuffer Buffer where the rebuilt IAT will be stored.
+ **/
+ void IatDirectory::rebuild(std::vector<byte>& vBuffer) const
+ {
+ vBuffer.reserve(size());
+ OutputBuffer obBuffer(vBuffer);
+
+ for (unsigned int i=0;i<m_vIat.size();i++)
+ {
+ obBuffer << m_vIat[i];
+ }
+ }
+
+ unsigned int IatDirectory::size() const
+ {
+ return static_cast<unsigned int>(m_vIat.size())* sizeof(dword);
+ }
+
+ /// Writes the current IAT to a file.
+ int IatDirectory::write(const std::string& strFilename, unsigned int uiOffset) const
+ {
+ std::fstream ofFile(strFilename.c_str(), std::ios_base::in);
+
+ if (!ofFile)
+ {
+ ofFile.clear();
+ ofFile.open(strFilename.c_str(), std::ios_base::out | std::ios_base::binary);
+ }
+ else
+ {
+ ofFile.close();
+ ofFile.open(strFilename.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary);
+ }
+
+ if (!ofFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ ofFile.seekp(uiOffset, std::ios::beg);
+
+ std::vector<unsigned char> vBuffer;
+ rebuild(vBuffer);
+
+ ofFile.write(reinterpret_cast<const char*>(&vBuffer[0]), static_cast<unsigned int>(vBuffer.size()));
+
+ ofFile.close();
+
+ return NO_ERROR;
+ }
+}
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h new file mode 100755 index 0000000000..81ef77ed6a --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/IatDirectory.h @@ -0,0 +1,58 @@ +/*
+* IatDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef IATDIRECTORY_H
+#define IATDIRECTORY_H
+
+#include "PeLibInc.h"
+
+namespace PeLib
+{
+ /// Class that handles the Import Address Table (IAT)
+ /**
+ * This class can read and modify the Import Address Table of a PE file.
+ **/
+ class IatDirectory
+ {
+ private:
+ std::vector<dword> m_vIat; ///< Stores the individual IAT fields.
+
+ int read(InputBuffer& inputBuffer, unsigned int size);
+
+ public:
+ /// Reads the Import Address Table from a PE file.
+ int read(const std::string& strFilename, unsigned int dwOffset, unsigned int dwSize); // EXPORT
+ int read(unsigned char* buffer, unsigned int buffersize); // EXPORT
+ /// Returns the number of fields in the IAT.
+ unsigned int calcNumberOfAddresses() const; // EXPORT
+ /// Adds another address to the IAT.
+ void addAddress(dword dwValue); // EXPORT
+ /// Removes an address from the IAT.
+ void removeAddress(unsigned int index); // EXPORT
+ /// Empties the IAT.
+ void clear(); // EXPORT
+ // Rebuilds the IAT.
+ void rebuild(std::vector<byte>& vBuffer) const; // EXPORT
+ /// Returns the size of the current IAT.
+ unsigned int size() const; // EXPORT
+ /// Writes the current IAT to a file.
+ int write(const std::string& strFilename, unsigned int uiOffset) const; // EXPORT
+
+ /// Retrieve the value of a field in the IAT.
+ dword getAddress(unsigned int index) const; // EXPORT
+ /// Change the value of a field in the IAT.
+ void setAddress(dword dwAddrnr, dword dwValue); // EXPORT
+ };
+}
+
+#endif
+
diff --git a/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h new file mode 100755 index 0000000000..6578f0712a --- /dev/null +++ b/utils/zenutils/libraries/pelib-0.9/pelib/ImportDirectory.h @@ -0,0 +1,1139 @@ +/*
+* ImportDirectory.h - Part of the PeLib library.
+*
+* Copyright (c) 2004 - 2005 Sebastian Porst (webmaster@the-interweb.com)
+* All rights reserved.
+*
+* This software is licensed under the zlib/libpng License.
+* For more details see http://www.opensource.org/licenses/zlib-license.php
+* or the license information file (license.htm) in the root directory
+* of PeLib.
+*/
+
+#ifndef IMPORTDIRECTORY_H
+#define IMPORTDIRECTORY_H
+
+#include "PeLibAux.h"
+#include "PeHeader.h"
+
+namespace PeLib
+{
+ /// Parameter for functions that can operate on the OLDDIR or new import directory.
+ enum currdir {OLDDIR = 1, NEWDIR};
+
+ class PeLibException;
+
+ /// Class that handles import directories.
+ /**
+ * This class can read import directories from existing PE files or start completely from scratch.
+ * Modifying import directories and writing them to files is also possible.
+ * It's worthy to note that many functions require an extra parameter of type currdir
+ * because the structure of import directories make it necessary that the OLDDIR import directory
+ * must be preserved. That's why some functions (like adding and removing) imported functions
+ * only exist for the new import directory, not for the one which is already written to the file.
+ * \todo Adding functions by ordinal doesn't work yet (rebuild needs to be changed).
+ * \todo Somehow store the rvas of the chunks in the file.
+ **/
+ template<int bits>
+ class ImportDirectory
+ {
+ typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::iterator ImpDirFileIterator;
+ typedef typename std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >::const_iterator ConstImpDirFileIterator;
+
+ private:
+ /// Stores information about already imported DLLs.
+ std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vOldiid;
+ /// Stores information about imported DLLs which will be added.
+ std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > m_vNewiid;
+
+ // I can't convince Borland C++ to compile the function outside of the class declaration.
+ // That's why the function definition is here.
+ /// Tests if a certain function is imported.
+ template<typename T> bool hasFunction(std::string strFilename, T value, bool(PELIB_THUNK_DATA<bits>::* comp)(T) const) const
+ {
+ ConstImpDirFileIterator FileIter = m_vOldiid.begin();
+ ConstImpDirFileIterator EndIter = m_vOldiid.end();
+
+ for (int i=0;i<=1;i++) // Loop once for m_vOldiid and once for m_vNewiid
+ {
+ do
+ {
+ FileIter = std::find_if(FileIter, EndIter, std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
+
+ if (FileIter != EndIter)
+ {
+ typename std::vector<PELIB_THUNK_DATA<bits> >::const_iterator Iter = std::find_if(FileIter->originalfirstthunk.begin(), FileIter->originalfirstthunk.end(), std::bind2nd(std::mem_fun_ref(comp), value));
+ if (Iter != FileIter->originalfirstthunk.end())
+ {
+ return true;
+ }
+ ++FileIter;
+ }
+ }
+ while (FileIter != EndIter);
+
+ FileIter = m_vNewiid.begin();
+ EndIter = m_vNewiid.end();
+ }
+
+ return false;
+ }
+
+
+ public:
+
+ /// Add a function to the import directory.
+ int addFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
+ /// Add a function to the import directory.
+ int addFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
+
+ /// Get the ID of a file through it's name.
+ unsigned int getFileIndex(const std::string& strFilename, currdir cdDir) const; // EXPORT
+ /// Get the ID of a function through it's name.
+ unsigned int getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const; // EXPORT
+
+ /// Get the name of an imported file.
+ std::string getFileName(dword dwFilenr, currdir cdDir) const; // EXPORT
+
+ void setFileName(dword filenr, currdir dir, const std::string& name); // EXPORT
+
+ /// Get the hint of an imported function.
+ word getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
+ void setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value); // EXPORT
+ /// Get the name of an imported function.
+ std::string getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT
+ void setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName); // EXPORT
+ /// Get the number of files which are imported.
+ dword getNumberOfFiles(currdir cdDir) const; // EXPORT
+ /// Get the number of fucntions which are imported by a specific file.
+ dword getNumberOfFunctions(dword dwFilenr, currdir cdDir) const; // EXPORT
+ /// Read a file's import directory.
+ int read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader); // EXPORT
+ /// Rebuild the import directory.
+ void rebuild(std::vector<byte>& vBuffer, dword dwRva, bool fixEntries = true) const; // EXPORT
+ /// Remove a file from the import directory.
+ int removeFile(const std::string& strFilename); // EXPORT
+ /// Remove a function from the import directory.
+ int removeFunction(const std::string& strFilename, const std::string& strFuncname); // EXPORT _byName
+ /// Remove a function from the import directory.
+ int removeFunction(const std::string& strFilename, word wHint); // EXPORT _byHint
+ /// Returns the size of the current import directory.
+ unsigned int size() const; // EXPORT
+ /// Writes the import directory to a file.
+ int write(const std::string& strFilename, unsigned int uiOffset, unsigned int uiRva); // EXPORT
+
+ /// Returns the FirstThunk value of a function.
+ dword getFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
+ void setFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT _byNumber
+ /// Returns the OriginalFirstThunk value of a function.
+ dword getOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir) const; // EXPORT _byNumber
+ void setOriginalFirstThunk(dword dwFilenr, dword dwFuncnr, currdir cdDir, dword value); // EXPORT
+
+// dword getFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
+// dword getOriginalFirstThunk(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
+
+ /// Returns the FirstThunk value of a file.
+ dword getFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
+ /// Returns the OriginalFirstThunk value of a file.
+ dword getOriginalFirstThunk(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
+ /// Returns the ForwarderChain value of a file.
+ dword getForwarderChain(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
+ dword getRvaOfName(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
+ /// Returns the TimeDateStamp value of a file.
+ dword getTimeDateStamp(const std::string& strFilename, currdir cdDir) const; // EXPORT _byName
+
+ /// Returns the FirstThunk value of a file.
+ dword getFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
+ void setFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
+ /// Returns the OriginalFirstThunk value of a file.
+ dword getOriginalFirstThunk(dword dwFilenr, currdir cdDir) const; // EXPORT
+ void setOriginalFirstThunk(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
+ /// Returns the ForwarderChain value of a file.
+ dword getForwarderChain(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
+ void setForwarderChain(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber_function
+ dword getRvaOfName(dword dwFilenr, currdir cdDir) const; // EXPORT _byNumber
+ void setRvaOfName(dword dwFilenr, currdir cdDir, dword value); // EXPORT
+ /// Returns the TimeDateStamp value of a file.
+ dword getTimeDateStamp(dword dwFilenr, currdir cdDir) const; // EXPORT
+ void setTimeDateStamp(dword dwFilenr, currdir cdDir, dword value); // EXPORT _byNumber
+
+// word getFunctionHint(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const throw (PeLibException);
+ };
+
+ /**
+ * Add another import (by Ordinal) to the current file. Note that the import table is not automatically updated.
+ * The new imported functions will be added when you recalculate the import table as it's necessary
+ * to specify the address the import table will have in the file.
+ * @param strFilename The name of a DLL.
+ * @param wHint The ordinal of the function in the DLL.
+ **/
+ template<int bits>
+ int ImportDirectory<bits>::addFunction(const std::string& strFilename, word wHint)
+ {
+ if (hasFunction(strFilename, wHint, &PELIB_THUNK_DATA<bits>::equalHint))
+ {
+ return ERROR_DUPLICATE_ENTRY;
+ }
+
+ // Find the imported file.
+ ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
+
+ PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
+ PELIB_THUNK_DATA<bits> td;
+ td.hint = wHint;
+ td.itd.Ordinal = wHint | PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG;
+ iid.name = strFilename;
+ if (FileIter == m_vNewiid.end())
+ {
+ iid.originalfirstthunk.push_back(td);
+ iid.firstthunk.push_back(td);
+ m_vNewiid.push_back(iid);
+ }
+ else
+ {
+ FileIter->originalfirstthunk.push_back(td);
+ FileIter->firstthunk.push_back(td);
+ }
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Add a function to the Import Directory.
+ * @param strFilename Name of the file which will be imported
+ * @param strFuncname Name of the function which will be imported.
+ **/
+ template<int bits>
+ int ImportDirectory<bits>::addFunction(const std::string& strFilename, const std::string& strFuncname)
+ {
+ if (hasFunction(strFilename, strFuncname, &PELIB_THUNK_DATA<bits>::equalFunctionName))
+ {
+ return ERROR_DUPLICATE_ENTRY;
+ }
+
+ // Find the imported file.
+ ImpDirFileIterator FileIter = std::find_if(m_vNewiid.begin(), m_vNewiid.end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
+
+ PELIB_IMAGE_IMPORT_DIRECTORY<bits> iid;
+ PELIB_THUNK_DATA<bits> td;
+ td.fname = strFuncname;
+ iid.name = strFilename;
+ if (FileIter == m_vNewiid.end())
+ {
+ iid.originalfirstthunk.push_back(td);
+ iid.firstthunk.push_back(td);
+ m_vNewiid.push_back(iid);
+ }
+ else
+ {
+ FileIter->originalfirstthunk.push_back(td);
+ FileIter->firstthunk.push_back(td);
+ }
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Searches through the import directory and returns the number of the import
+ * directory entry which belongs to the given filename.
+ * @param strFilename Name of the imported file.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return The ID of an imported file.
+ **/
+ template<int bits>
+ unsigned int ImportDirectory<bits>::getFileIndex(const std::string& strFilename, currdir cdDir) const
+ {
+ const std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> >* currDir;
+
+ if (cdDir == OLDDIR)
+ {
+ currDir = &m_vOldiid;
+ }
+ else
+ {
+ currDir = &m_vNewiid;
+ }
+
+ ConstImpDirFileIterator FileIter = std::find_if(currDir->begin(), currDir->end(), std::bind2nd(std::mem_fun_ref(&PELIB_IMAGE_IMPORT_DIRECTORY<bits>::operator==), strFilename));
+
+ if (FileIter != currDir->end())
+ {
+ return static_cast<unsigned int>(std::distance(currDir->begin(), FileIter));
+ }
+ else
+ {
+ return -1;
+ // throw Exceptions::InvalidName(ImportDirectoryId, __LINE__);
+ }
+
+ return NO_ERROR;
+ }
+
+ /**
+ * Searches through an imported file for a specific function.
+ * @param strFilename Name of the imported file.
+ * @param strFuncname Name of the imported function.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return ID of the imported function.
+ **/
+ template<int bits>
+ unsigned int ImportDirectory<bits>::getFunctionIndex(const std::string& strFilename, const std::string& strFuncname, currdir cdDir) const
+ {
+ unsigned int uiFile = getFileIndex(strFilename, cdDir);
+
+ for (unsigned int i=0;i<getNumberOfFunctions(uiFile, cdDir);i++)
+ {
+ if (getFunctionName(uiFile, i, cdDir) == strFuncname) return i;
+ }
+
+ return -1;
+ }
+
+ /**
+ * Get the name of an imported file.
+ * @param dwFilenr Identifies which file should be checked.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return Name of an imported file.
+ **/
+ template<int bits>
+ std::string ImportDirectory<bits>::getFileName(dword dwFilenr, currdir cdDir) const
+ {
+ if (cdDir == OLDDIR) return m_vOldiid[dwFilenr].name;
+ else return m_vNewiid[dwFilenr].name;
+ }
+
+ template<int bits>
+ void ImportDirectory<bits>::setFileName(dword filenr, currdir dir, const std::string& name)
+ {
+ if (dir == OLDDIR) m_vOldiid[filenr].name = name;
+ else m_vNewiid[filenr].name = name;
+ }
+
+ /**
+ * Get the name of an imported function.
+ * @param dwFilenr Identifies which file should be checked.
+ * @param dwFuncnr Identifies which function should be checked.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return Name of an imported function.
+ * \todo Marked line is unsafe (function should be rewritten).
+ **/
+ template<int bits>
+ std::string ImportDirectory<bits>::getFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
+ {
+ if (cdDir == OLDDIR)
+ {
+ // Unsafe
+ if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
+ }
+ else
+ {
+ return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname;
+ }
+ }
+ else
+ {
+ if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname;
+ }
+ else
+ {
+ return m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname;
+ }
+ }
+ }
+
+ template<int bits>
+ void ImportDirectory<bits>::setFunctionName(dword dwFilenr, dword dwFuncnr, currdir cdDir, const std::string& functionName)
+ {
+ if (cdDir == OLDDIR)
+ {
+ // Unsafe
+ if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
+ }
+ else
+ {
+ m_vOldiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
+ }
+ }
+ else
+ {
+ if (m_vNewiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].fname = functionName;
+ }
+ else
+ {
+ m_vNewiid[dwFilenr].firstthunk[dwFuncnr].fname = functionName;
+ }
+ }
+ }
+
+ /**
+ * Get the hint of an imported function.
+ * @param dwFilenr Identifies which file should be checked.
+ * @param dwFuncnr Identifies which function should be checked.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return Hint of an imported function.
+ **/
+ template<int bits>
+ word ImportDirectory<bits>::getFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir) const
+ {
+ if (cdDir == OLDDIR)
+ {
+ if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ return m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
+ }
+ else
+ {
+ return m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint;
+ }
+ }
+ else return m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint;
+ }
+
+ template<int bits>
+ void ImportDirectory<bits>::setFunctionHint(dword dwFilenr, dword dwFuncnr, currdir cdDir, word value)
+ {
+ if (cdDir == OLDDIR)
+ {
+ if (m_vOldiid[dwFilenr].impdesc.OriginalFirstThunk)
+ {
+ m_vOldiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
+ }
+ else
+ {
+ m_vOldiid[dwFilenr].firstthunk[dwFuncnr].hint = value;
+ }
+ }
+ else m_vNewiid[dwFilenr].originalfirstthunk[dwFuncnr].hint = value;
+ }
+
+ /**
+ * Get the number of files which are currently being imported.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return Number of files which are currently being imported.
+ **/
+ template<int bits>
+ dword ImportDirectory<bits>::getNumberOfFiles(currdir cdDir) const
+ {
+ if (cdDir == OLDDIR) return static_cast<dword>(m_vOldiid.size());
+ else return static_cast<dword>(m_vNewiid.size());
+ }
+
+ /**
+ * Get the number of functions which are currently being imported from a specific file.
+ * @param dwFilenr Identifies which file should be checked.
+ * @param cdDir Flag to decide if the OLDDIR or new import directory is used.
+ * @return Number of functions which are currently being imported from a specific file.
+ **/
+ template<int bits>
+ dword ImportDirectory<bits>::getNumberOfFunctions(dword dwFilenr, currdir cdDir) const
+ {
+ if (cdDir == OLDDIR) return static_cast<unsigned int>(m_vOldiid[dwFilenr].firstthunk.size());
+ else return static_cast<unsigned int>(m_vNewiid[dwFilenr].firstthunk.size());
+ }
+
+ /**
+ * Read an import directory from a file.
+ * \todo Check if streams failed.
+ * @param strFilename Name of the file which will be read.
+ * @param uiOffset Offset of the import directory (see #PeLib::PeHeader::getIDImportRVA).
+ * @param uiSize Size of the import directory (see #PeLib::PeHeader::getIDImportSize).
+ * @param pehHeader A valid PE header.
+ **/
+ template<int bits>
+ int ImportDirectory<bits>::read(const std::string& strFilename, unsigned int uiOffset, unsigned int uiSize, const PeHeaderT<bits>& pehHeader)
+ {
+ std::ifstream ifFile(strFilename.c_str(), std::ios_base::binary);
+
+ if (!ifFile)
+ {
+ return ERROR_OPENING_FILE;
+ }
+
+ unsigned int uiFileSize = fileSize(ifFile);
+
+ if (uiFileSize < uiOffset + uiSize)
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ ifFile.seekg(uiOffset, std::ios_base::beg);
+
+ std::vector<unsigned char> vImportdirectory(uiSize);
+ ifFile.read(reinterpret_cast<char*>(&vImportdirectory[0]), uiSize);
+
+ PELIB_IMAGE_IMPORT_DIRECTORY<bits> iidCurr;
+ unsigned int uiDesccounter = 0;
+
+ InputBuffer inpBuffer(vImportdirectory);
+
+ std::vector<PELIB_IMAGE_IMPORT_DIRECTORY<bits> > vOldIidCurr;
+
+ do // Read and store all descriptors
+ {
+ inpBuffer >> iidCurr.impdesc.OriginalFirstThunk;
+ inpBuffer >> iidCurr.impdesc.TimeDateStamp;
+ inpBuffer >> iidCurr.impdesc.ForwarderChain;
+ inpBuffer >> iidCurr.impdesc.Name;
+ inpBuffer >> iidCurr.impdesc.FirstThunk;
+
+ if (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
+ iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0)
+ {
+ vOldIidCurr.push_back(iidCurr);
+ }
+
+ uiDesccounter++;
+
+ if (uiSize < (uiDesccounter + 1) * PELIB_IMAGE_IMPORT_DESCRIPTOR::size()) break;
+ } while (iidCurr.impdesc.OriginalFirstThunk != 0 || iidCurr.impdesc.TimeDateStamp != 0 || iidCurr.impdesc.ForwarderChain != 0 ||
+ iidCurr.impdesc.Name != 0 || iidCurr.impdesc.FirstThunk != 0);
+
+ char namebuffer[2] = {0};
+
+ // Name
+ for (unsigned int i=0;i<vOldIidCurr.size();i++)
+ {
+ ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].impdesc.Name)), std::ios_base::beg);
+
+ std::string dllname = "";
+
+ do
+ {
+ ifFile.read(namebuffer, 1);
+ if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
+ dllname += namebuffer;
+ } while (true);
+
+ vOldIidCurr[i].name = dllname;
+
+ }
+
+ // OriginalFirstThunk
+ for (unsigned int i=0;i<vOldIidCurr.size();i++)
+ {
+ PELIB_THUNK_DATA<bits> tdCurr;
+ dword uiVaoft = vOldIidCurr[i].impdesc.OriginalFirstThunk;
+
+ if (!uiVaoft)
+ {
+ continue;
+ }
+
+ ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
+
+ do
+ {
+ if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
+ {
+ return ERROR_INVALID_FILE;
+ }
+ uiVaoft += sizeof(tdCurr.itd.Ordinal);
+
+ ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
+ if (tdCurr.itd.Ordinal) vOldIidCurr[i].originalfirstthunk.push_back(tdCurr);
+ } while (tdCurr.itd.Ordinal);
+ }
+
+ // FirstThunk
+ for (unsigned int i=0;i<vOldIidCurr.size();i++)
+ {
+ dword uiVaoft = vOldIidCurr[i].impdesc.FirstThunk;
+ PELIB_THUNK_DATA<bits> tdCurr;
+
+ ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(uiVaoft)), std::ios_base::beg);
+
+ do
+ {
+ if (uiFileSize < pehHeader.rvaToOffset(uiVaoft) + sizeof(tdCurr.itd.Ordinal))
+ {
+ return ERROR_INVALID_FILE;
+ }
+
+ uiVaoft += sizeof(tdCurr.itd.Ordinal);
+
+ ifFile.read(reinterpret_cast<char*>(&tdCurr.itd.Ordinal), sizeof(tdCurr.itd.Ordinal));
+ if (tdCurr.itd.Ordinal) vOldIidCurr[i].firstthunk.push_back(tdCurr);
+ } while (tdCurr.itd.Ordinal);
+ }
+
+ // Names
+ for (unsigned int i=0;i<vOldIidCurr.size();i++)
+ {
+ if (vOldIidCurr[i].impdesc.OriginalFirstThunk)
+ {
+ for (unsigned int j=0;j<vOldIidCurr[i].originalfirstthunk.size();j++)
+ {
+ if (vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
+ {
+ vOldIidCurr[i].originalfirstthunk[j].hint = 0;
+ continue;
+ }
+
+ ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].originalfirstthunk[j].itd.Ordinal)), std::ios_base::beg);
+
+ ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].originalfirstthunk[j].hint), sizeof(vOldIidCurr[i].originalfirstthunk[j].hint));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ std::string funcname = "";
+ do
+ {
+ ifFile.read(namebuffer, 1);
+ if (!ifFile || !namebuffer[0]) break; // reached end of file or 0-byte
+ funcname += namebuffer;
+ } while (true);
+
+ vOldIidCurr[i].originalfirstthunk[j].fname = funcname;
+ }
+ }
+ else
+ {
+ for (unsigned int j=0;j<vOldIidCurr[i].firstthunk.size();j++)
+ {
+ if (vOldIidCurr[i].firstthunk[j].itd.Ordinal & PELIB_IMAGE_ORDINAL_FLAGS<bits>::IMAGE_ORDINAL_FLAG)
+ {
+ continue;
+ }
+
+ ifFile.seekg(static_cast<unsigned int>(pehHeader.rvaToOffset(vOldIidCurr[i].firstthunk[j].itd.Ordinal)), std::ios_base::beg);
+
+ ifFile.read(reinterpret_cast<char*>(&vOldIidCurr[i].firstthunk[j].hint), sizeof(vOldIidCurr[i].firstthunk[j].hint));
+
+ if (!ifFile)
+ return ERROR_INVALID_FILE;
+
+ std::string funcname = "";
+ do
+ {
+ |