From e0a744149d1c403d736e88863cf706ff2713d029 Mon Sep 17 00:00:00 2001 From: Viktor Szakats Date: Mon, 23 Jun 2008 22:34:45 +0000 Subject: [PATCH] 2008-06-24 00:33 UTC+0200 Viktor Szakats (harbour.01 syenar hu) + contrib/hbziparch/readme.txt + contrib/hbziparch/zlib + contrib/hbziparch/zlib/deflate.h + contrib/hbziparch/zlib/zlib.h * contrib/hbziparch/common.mak * contrib/hbziparch/hbcomprs.c * contrib/hbziparch/hbziparc.c * contrib/hbziparch/hbzipcom.cpp * contrib/hbziparch/hbzipnew.cpp * contrib/hbziparch/License.txt * contrib/hbziparch/make_gcc.sh * contrib/hbziparch/make_vc.bat * contrib/hbziparch/Makefile * contrib/hbziparch/resource.h * contrib/hbziparch/stdafx.h * contrib/hbziparch/ZipExport.h * contrib/hbziparch/ZipPathComponent_lnx.cpp * contrib/hbziparch/ZipPathComponent_win.cpp * contrib/hbziparch/ZipPlatform_lnx.cpp * contrib/hbziparch/ZipPlatform_win.cpp * contrib/hbziparch/ZipString.cpp - contrib/hbziparch/stdafx.cpp - contrib/hbziparch/zipabstractfile.h - contrib/hbziparch/ziparchive.cpp - contrib/hbziparch/ziparchive.h - contrib/hbziparch/zipautobuffer.cpp - contrib/hbziparch/zipautobuffer.h - contrib/hbziparch/zipbaseexception.h - contrib/hbziparch/zipcentraldir.cpp - contrib/hbziparch/zipcentraldir.h - contrib/hbziparch/zipcollections.h - contrib/hbziparch/zipcompatibility.cpp - contrib/hbziparch/zipcompatibility.h - contrib/hbziparch/zipexception.cpp - contrib/hbziparch/zipexception.h - contrib/hbziparch/zipfile.cpp - contrib/hbziparch/zipfile.h - contrib/hbziparch/zipfileheader.cpp - contrib/hbziparch/zipfileheader.h - contrib/hbziparch/zipfilemapping.h - contrib/hbziparch/zipinternalinfo.h - contrib/hbziparch/zipmemfile.cpp - contrib/hbziparch/zipmemfile.h - contrib/hbziparch/zippathcomponent.h - contrib/hbziparch/zipplatform.h - contrib/hbziparch/zipplatformcomm.cpp - contrib/hbziparch/zipstorage.cpp - contrib/hbziparch/zipstorage.h - contrib/hbziparch/zipstring.h * ZipArchive 2.x -> ZipArchive 3.2.0 (latest) Only one minor modification (reported to author) Plus integrated ZLIB replaced with hbzlib. ; Pass 1 --- harbour/ChangeLog | 55 + harbour/contrib/hbziparch/License.txt | 331 +- harbour/contrib/hbziparch/Makefile | 44 +- harbour/contrib/hbziparch/ZipExport.h | 33 +- .../hbziparch/ZipPathComponent_lnx.cpp | 23 +- .../hbziparch/ZipPathComponent_win.cpp | 32 +- harbour/contrib/hbziparch/ZipPlatform_lnx.cpp | 170 +- harbour/contrib/hbziparch/ZipPlatform_win.cpp | 277 +- harbour/contrib/hbziparch/ZipString.cpp | 13 +- harbour/contrib/hbziparch/common.mak | 44 +- harbour/contrib/hbziparch/hbcomprs.c | 27 +- harbour/contrib/hbziparch/hbziparc.c | 33 +- harbour/contrib/hbziparch/hbzipcom.cpp | 153 +- harbour/contrib/hbziparch/hbzipnew.cpp | 109 +- harbour/contrib/hbziparch/make_gcc.sh | 2 - harbour/contrib/hbziparch/make_vc.bat | 2 +- harbour/contrib/hbziparch/readme.txt | 73 + harbour/contrib/hbziparch/resource.h | 2 +- harbour/contrib/hbziparch/stdafx.cpp | 20 - harbour/contrib/hbziparch/stdafx.h | 164 +- harbour/contrib/hbziparch/zipabstractfile.h | 54 - harbour/contrib/hbziparch/ziparchive.cpp | 3235 ----------------- harbour/contrib/hbziparch/ziparchive.h | 2050 ----------- harbour/contrib/hbziparch/zipautobuffer.cpp | 108 - harbour/contrib/hbziparch/zipautobuffer.h | 78 - harbour/contrib/hbziparch/zipbaseexception.h | 22 - harbour/contrib/hbziparch/zipcentraldir.cpp | 852 ----- harbour/contrib/hbziparch/zipcentraldir.h | 554 --- harbour/contrib/hbziparch/zipcollections.h | 171 - .../contrib/hbziparch/zipcompatibility.cpp | 214 -- harbour/contrib/hbziparch/zipcompatibility.h | 107 - harbour/contrib/hbziparch/zipexception.cpp | 280 -- harbour/contrib/hbziparch/zipexception.h | 228 -- harbour/contrib/hbziparch/zipfile.cpp | 116 - harbour/contrib/hbziparch/zipfile.h | 116 - harbour/contrib/hbziparch/zipfileheader.cpp | 340 -- harbour/contrib/hbziparch/zipfileheader.h | 352 -- harbour/contrib/hbziparch/zipfilemapping.h | 132 - harbour/contrib/hbziparch/zipinternalinfo.h | 60 - harbour/contrib/hbziparch/zipmemfile.cpp | 98 - harbour/contrib/hbziparch/zipmemfile.h | 108 - harbour/contrib/hbziparch/zippathcomponent.h | 206 -- harbour/contrib/hbziparch/zipplatform.h | 175 - harbour/contrib/hbziparch/zipplatformcomm.cpp | 49 - harbour/contrib/hbziparch/zipstorage.cpp | 463 --- harbour/contrib/hbziparch/zipstorage.h | 588 --- harbour/contrib/hbziparch/zipstring.h | 310 -- harbour/contrib/hbziparch/zlib/deflate.h | 5 + harbour/contrib/hbziparch/zlib/zlib.h | 94 + 49 files changed, 1152 insertions(+), 11620 deletions(-) create mode 100644 harbour/contrib/hbziparch/readme.txt delete mode 100644 harbour/contrib/hbziparch/stdafx.cpp delete mode 100644 harbour/contrib/hbziparch/zipabstractfile.h delete mode 100644 harbour/contrib/hbziparch/ziparchive.cpp delete mode 100644 harbour/contrib/hbziparch/ziparchive.h delete mode 100644 harbour/contrib/hbziparch/zipautobuffer.cpp delete mode 100644 harbour/contrib/hbziparch/zipautobuffer.h delete mode 100644 harbour/contrib/hbziparch/zipbaseexception.h delete mode 100644 harbour/contrib/hbziparch/zipcentraldir.cpp delete mode 100644 harbour/contrib/hbziparch/zipcentraldir.h delete mode 100644 harbour/contrib/hbziparch/zipcollections.h delete mode 100644 harbour/contrib/hbziparch/zipcompatibility.cpp delete mode 100644 harbour/contrib/hbziparch/zipcompatibility.h delete mode 100644 harbour/contrib/hbziparch/zipexception.cpp delete mode 100644 harbour/contrib/hbziparch/zipexception.h delete mode 100644 harbour/contrib/hbziparch/zipfile.cpp delete mode 100644 harbour/contrib/hbziparch/zipfile.h delete mode 100644 harbour/contrib/hbziparch/zipfileheader.cpp delete mode 100644 harbour/contrib/hbziparch/zipfileheader.h delete mode 100644 harbour/contrib/hbziparch/zipfilemapping.h delete mode 100644 harbour/contrib/hbziparch/zipinternalinfo.h delete mode 100644 harbour/contrib/hbziparch/zipmemfile.cpp delete mode 100644 harbour/contrib/hbziparch/zipmemfile.h delete mode 100644 harbour/contrib/hbziparch/zippathcomponent.h delete mode 100644 harbour/contrib/hbziparch/zipplatform.h delete mode 100644 harbour/contrib/hbziparch/zipplatformcomm.cpp delete mode 100644 harbour/contrib/hbziparch/zipstorage.cpp delete mode 100644 harbour/contrib/hbziparch/zipstorage.h delete mode 100644 harbour/contrib/hbziparch/zipstring.h create mode 100644 harbour/contrib/hbziparch/zlib/deflate.h create mode 100644 harbour/contrib/hbziparch/zlib/zlib.h diff --git a/harbour/ChangeLog b/harbour/ChangeLog index 9131d1c44c..ee16ca018b 100644 --- a/harbour/ChangeLog +++ b/harbour/ChangeLog @@ -8,6 +8,61 @@ 2008-12-31 13:59 UTC+0100 Foo Bar */ +2008-06-24 00:33 UTC+0200 Viktor Szakats (harbour.01 syenar hu) + + contrib/hbziparch/readme.txt + + contrib/hbziparch/zlib + + contrib/hbziparch/zlib/deflate.h + + contrib/hbziparch/zlib/zlib.h + * contrib/hbziparch/common.mak + * contrib/hbziparch/hbcomprs.c + * contrib/hbziparch/hbziparc.c + * contrib/hbziparch/hbzipcom.cpp + * contrib/hbziparch/hbzipnew.cpp + * contrib/hbziparch/License.txt + * contrib/hbziparch/make_gcc.sh + * contrib/hbziparch/make_vc.bat + * contrib/hbziparch/Makefile + * contrib/hbziparch/resource.h + * contrib/hbziparch/stdafx.h + * contrib/hbziparch/ZipExport.h + * contrib/hbziparch/ZipPathComponent_lnx.cpp + * contrib/hbziparch/ZipPathComponent_win.cpp + * contrib/hbziparch/ZipPlatform_lnx.cpp + * contrib/hbziparch/ZipPlatform_win.cpp + * contrib/hbziparch/ZipString.cpp + - contrib/hbziparch/stdafx.cpp + - contrib/hbziparch/zipabstractfile.h + - contrib/hbziparch/ziparchive.cpp + - contrib/hbziparch/ziparchive.h + - contrib/hbziparch/zipautobuffer.cpp + - contrib/hbziparch/zipautobuffer.h + - contrib/hbziparch/zipbaseexception.h + - contrib/hbziparch/zipcentraldir.cpp + - contrib/hbziparch/zipcentraldir.h + - contrib/hbziparch/zipcollections.h + - contrib/hbziparch/zipcompatibility.cpp + - contrib/hbziparch/zipcompatibility.h + - contrib/hbziparch/zipexception.cpp + - contrib/hbziparch/zipexception.h + - contrib/hbziparch/zipfile.cpp + - contrib/hbziparch/zipfile.h + - contrib/hbziparch/zipfileheader.cpp + - contrib/hbziparch/zipfileheader.h + - contrib/hbziparch/zipfilemapping.h + - contrib/hbziparch/zipinternalinfo.h + - contrib/hbziparch/zipmemfile.cpp + - contrib/hbziparch/zipmemfile.h + - contrib/hbziparch/zippathcomponent.h + - contrib/hbziparch/zipplatform.h + - contrib/hbziparch/zipplatformcomm.cpp + - contrib/hbziparch/zipstorage.cpp + - contrib/hbziparch/zipstorage.h + - contrib/hbziparch/zipstring.h + * ZipArchive 2.x -> ZipArchive 3.2.0 (latest) + Only one minor modification (reported to author) + Plus integrated ZLIB replaced with hbzlib. + ; Pass 1 + 2008-06-24 00:21 UTC+0200 Viktor Szakats (harbour.01 syenar hu) + contrib/hbziparch/tests + contrib/hbziparch/tests/bld_b32.bat diff --git a/harbour/contrib/hbziparch/License.txt b/harbour/contrib/hbziparch/License.txt index 0fd5e9833c..f6018006a7 100644 --- a/harbour/contrib/hbziparch/License.txt +++ b/harbour/contrib/hbziparch/License.txt @@ -1,73 +1,284 @@ -/** \page pageLic Licensing information +The ZipArchive Library is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz +For the licensing details, please visit: +http://www.artpol-software.com/ZipArchive/KB/license.aspx +------------------------------------------------------------------ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 -ZipArchive library - creation, modification and decompression of "zip" format archives
-Copyright © 2000 - 2002 Tadeusz Dracz.
-E-Mail: \htmlonly tdracz@artpol-software.com
-Web: http://www.artpol-software.com \endhtmlonly + 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. -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. + Preamble -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 General Public License for more details. - -You should have received a copy of the GNU 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 + 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. -
-************************************************************************* -An English version of the \ref pageGPL "GNU GPL" is in the gpl.txt file distributed with -this project. Translations to other languages are available at: -\htmlonly -http://www.gnu.org/copyleft/gpl.html -\endhtmlonly + 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. - -Distributing ZipArchive under GNU GPL implies ZipArchive can only be used -with software that is licensed under conditions compliant with the GPL. -Embedding in proprietary software requires an alternative license. - + 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. -\subsection s1 Alternative license for use with proprietary software + 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. -If you want to distribute software in a commercial context that incorporates -ZipArchive and you do not want to meet the conditions of GNU GPL -(e.g. an obligation to provide a customer with the source code of your -software that uses the ZipArchive library), you need to have a commercial license. -- The commercial license provides you with the same rights as the GNU GPL, but in -addition allows you to embed ZipArchive library in proprietary software without -affecting the copyright of this software (it removes the GNU GPL obligation -to publish the source code) -- The license gives you royalty free distribution rights -- The license does not allow you to transfer these rights -- The license is granted per developer -- You won't need to purchase an additional license for the future versions of the library + 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 commercial license is available free of charge for using ZipArchive library in: -- freeware software (freeware is software that is available free of charge, but which is copyrighted by the developer, who retains the right to control its redistribution and to sell it in the future) - - excluded is software which is associated with an equipment that the same company manufactures and which has no practical usage value without it (e.g. software used for maintenace of machines) - unless the equipment is free as well (?) - - if you decide to sell the software in the future - you will need to purchase the commercial license for using the ZipArchive library, unless it is distributed in the shareware way - see below -- software distributed in the Shareware way (Shareware distribution gives users a chance to try software before buying it. If you try a Shareware program and continue using it, you are expected to register. Individual programs differ on details -- some request registration while others require it, some specify a maximum trial period. -Copyright laws apply to both Shareware and commercial software and the copyright holder retains all rights, with the exception that copying and distributing the program for evaluation purposes is encouraged, subject to certain conditions. For example, some authors require written permission before a commercial disk vendor may copy their Shareware. ) - - excluded is software which price for a single copy is higher than the price of the ZipArchive library for a single developer + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -Extended Licence for HBZLIB (library for zip compression in \htmlonly Harbour\endhtmlonly)
-You can create proprietary software using hbzlib respecting the follow: -- ZipArchive library must be linked together with hbzlib -- you cannot use ZipArchive as a dynamic library (DLL), it must be linked staticaly with the software -- the commercial license for ZipArchive is free of charge, but these grants are valid only if the whole application is written with Harbour + 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". -There is a fee for the commercial license for using the library in the software not falling into the mentioned categories. -
-It is recommended that you should print two copies of the commercial license -document after you receive it, sign them and send by post. One copy, signed by the author will be sent back to you. -Please \htmlonly contact the author or visit the Artpol Software web site\endhtmlonly to find out more. +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 diff --git a/harbour/contrib/hbziparch/Makefile b/harbour/contrib/hbziparch/Makefile index f71a93d281..72aae450e5 100644 --- a/harbour/contrib/hbziparch/Makefile +++ b/harbour/contrib/hbziparch/Makefile @@ -14,18 +14,34 @@ CPP_SOURCES = \ hbzipnew.cpp \ hbzipcom.cpp \ \ - stdafx.cpp \ - ziparchive.cpp \ - zipautobuffer.cpp \ - zipcentraldir.cpp \ - zipcompatibility.cpp \ - zipexception.cpp \ - zipfile.cpp \ - zipfileheader.cpp \ - zipmemfile.cpp \ - zipplatformcomm.cpp \ - zipstorage.cpp \ - ZipString.cpp + Aes.cpp \ + BaseLibCompressor.cpp \ + Bzip2Compressor.cpp \ + DeflateCompressor.cpp \ + DirEnumerator.cpp \ + FileFilter.cpp \ + Hmac.cpp \ + RandomPool.cpp \ + Sha1.cpp \ + Wildcard.cpp \ + ZipAesCryptograph.cpp \ + ZipArchive.cpp \ + ZipAutoBuffer.cpp \ + ZipCentralDir.cpp \ + ZipCompatibility.cpp \ + ZipCompressor.cpp \ + ZipCrc32Cryptograph.cpp \ + ZipCryptograph.cpp \ + ZipException.cpp \ + ZipExtraData.cpp \ + ZipExtraField.cpp \ +# ZipFile_mfc.cpp \ + ZipFile_stl.cpp \ + ZipFileHeader.cpp \ + ZipMemFile.cpp \ + ZipPlatformComm.cpp \ + ZipStorage.cpp \ + ZipString.cpp \ ifeq ($(HB_ARCHITECTURE),linux) CPP_SOURCES += \ @@ -43,4 +59,8 @@ PRG_SOURCES= \ LIBNAME=hbziparch +ifeq ($(HB_ARCHITECTURE),linux) +CFLAGS := $(CFLAGS) -DZIP_ARCHIVE_LNX +endif + include $(TOP)$(ROOT)config/lib.cf diff --git a/harbour/contrib/hbziparch/ZipExport.h b/harbour/contrib/hbziparch/ZipExport.h index 08c7ef4f69..f5c075795b 100644 --- a/harbour/contrib/hbziparch/ZipExport.h +++ b/harbour/contrib/hbziparch/ZipExport.h @@ -1,18 +1,35 @@ -#if !defined (ZIP_EXPORT_H) -#define ZIP_EXPORT_H +//////////////////////////////////////////////////////////////////////////////// +// This source file is part of the ZipArchive library source distribution and +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz +// +// 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. +// +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com +//////////////////////////////////////////////////////////////////////////////// + +/** +* \file ZipExport.h +* Contains the Windows DLL exports definitions. +* +*/ + + +#if !defined (ZIPARCHIVE_ZIPEXPORT_DOT_H) +#define ZIPARCHIVE_ZIPEXPORT_DOT_H #if defined (ZIP_HAS_DLL) -# if (ZIP_HAS_DLL == 1) # if defined (ZIP_BUILD_DLL) # define ZIP_API __declspec (dllexport) # else # define ZIP_API __declspec (dllimport) -# endif /* ZIP_BUILD_DLL */ -# else -# define ZIP_API -# endif /* ! ZIP_HAS_DLL == 1 */ +# endif #else # define ZIP_API #endif /* ZIP_HAS_DLL */ -#endif /* ZIP_EXPORT_H */ +#endif /* ZIPARCHIVE_ZIPEXPORT_DOT_H */ diff --git a/harbour/contrib/hbziparch/ZipPathComponent_lnx.cpp b/harbour/contrib/hbziparch/ZipPathComponent_lnx.cpp index 50bdda3895..c5dd2a5514 100644 --- a/harbour/contrib/hbziparch/ZipPathComponent_lnx.cpp +++ b/harbour/contrib/hbziparch/ZipPathComponent_lnx.cpp @@ -1,30 +1,27 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPathComponent.cpp $ -// $Archive: /ZipArchive_Linux/ZipPathComponent.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. // -// For the licensing details see the file License.txt +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// -#include "stdafx.h" -#include "zippathcomponent.h" +#include "_platform.h" -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// +#ifdef ZIP_ARCHIVE_LNX + +#include "stdafx.h" +#include "ZipPathComponent.h" CZipPathComponent::~CZipPathComponent() { - } void CZipPathComponent::SetFullPath(LPCTSTR lpszFullPath) @@ -83,7 +80,6 @@ void CZipPathComponent::SetFullPath(LPCTSTR lpszFullPath) } - CZipString CZipPathComponent::GetNoDrive() const { CZipString szPath = m_szDirectory; @@ -95,3 +91,4 @@ CZipString CZipPathComponent::GetNoDrive() const return szPath; } +#endif // ZIP_ARCHIVE_LNX diff --git a/harbour/contrib/hbziparch/ZipPathComponent_win.cpp b/harbour/contrib/hbziparch/ZipPathComponent_win.cpp index 79cb90560b..0f5d662f64 100644 --- a/harbour/contrib/hbziparch/ZipPathComponent_win.cpp +++ b/harbour/contrib/hbziparch/ZipPathComponent_win.cpp @@ -1,26 +1,23 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPathComponent.cpp $ -// $Archive: /ZipArchive/ZipPathComponent.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. // -// For the licensing details see the file License.txt +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// +#include "_platform.h" + +#ifdef ZIP_ARCHIVE_WIN + #include "stdafx.h" -#include "zippathcomponent.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - +#include "ZipPathComponent.h" CZipPathComponent::~CZipPathComponent() { @@ -31,7 +28,11 @@ void CZipPathComponent::SetFullPath(LPCTSTR lpszFullPath) { TCHAR szDrive[_MAX_DRIVE]; +#if defined _UNICODE && _MSC_VER >= 1400 + TCHAR szDir[32767]; +#else TCHAR szDir[_MAX_DIR]; +#endif TCHAR szFname[_MAX_FNAME]; TCHAR szExt[_MAX_EXT]; @@ -51,8 +52,12 @@ void CZipPathComponent::SetFullPath(LPCTSTR lpszFullPath) } else m_szPrefix.Empty(); - +#if _MSC_VER >= 1400 + _tsplitpath_s(szTempPath, szDrive , szDir, szFname, szExt); +#else _tsplitpath(szTempPath, szDrive , szDir, szFname, szExt); +#endif + m_szDrive = szDrive; m_szDirectory = szDir; @@ -74,3 +79,4 @@ CZipString CZipPathComponent::GetNoDrive() const return szPath; } +#endif // ZIP_ARCHIVE_WIN diff --git a/harbour/contrib/hbziparch/ZipPlatform_lnx.cpp b/harbour/contrib/hbziparch/ZipPlatform_lnx.cpp index f2240d4e13..01d0ad033c 100644 --- a/harbour/contrib/hbziparch/ZipPlatform_lnx.cpp +++ b/harbour/contrib/hbziparch/ZipPlatform_lnx.cpp @@ -1,40 +1,51 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPlatform.cpp $ -// $Archive: /ZipArchive_Linux/ZipPlatform.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. // -// For the licensing details see the file License.txt +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// +#include "_platform.h" + +#ifdef ZIP_ARCHIVE_LNX + +#if defined __APPLE__ || defined __CYGWIN__ + #define FILE_FUNCTIONS_64B_BY_DEFAULT +#else + #undef FILE_FUNCTIONS_64B_BY_DEFAULT +#endif #include "stdafx.h" -#include "zipplatform.h" -#include "zipfileheader.h" -#include "zipexception.h" -#include "zipautobuffer.h" - +#include "ZipPlatform.h" +#include "ZipFileHeader.h" +#include "ZipException.h" +#include "ZipAutoBuffer.h" #include +#include "ZipPathComponent.h" +#include "ZipCompatibility.h" +#include -#include "zippathcomponent.h" +#if defined (__FreeBSD__) || defined (__APPLE__) + #include + #include +#else + #include +#endif +#include - -#include "zipcompatibility.h" -#include #include #include -#include -#include + #include const TCHAR CZipPathComponent::m_cSeparator = _T('/'); @@ -43,70 +54,46 @@ const TCHAR CZipPathComponent::m_cSeparator = _T('/'); #define _utimbuf utimbuf #endif +#define ZIP_DEFAULT_DIR_ATTRIBUTES (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) + ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// -DWORD ZipPlatform::GetDeviceFreeSpace(LPCTSTR lpszPath) +ULONGLONG ZipPlatform::GetDeviceFreeSpace(LPCTSTR lpszPath) { struct statfs sStats; - if (statfs(lpszPath, &sStats) == -1) + + #if defined (__SVR4) && defined (__sun) + if (statvfs(lpszPath, &sStats) == -1) // Solaris + #else + if (statfs(lpszPath, &sStats) == -1) + #endif return 0; return sStats.f_bsize * sStats.f_bavail; } -bool ZipPlatform::GetFileSize(LPCTSTR lpszFileName, DWORD& dSize) -{ - int f = open(lpszFileName, O_RDONLY); - if (f == -1) - return false; - int iSize = lseek(f, 0, SEEK_END); - close(f); - if (iSize == -1) - return false; - dSize = (DWORD)iSize; - return true; -} -CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, DWORD iSizeNeeded) +CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, ZIP_SIZE_TYPE uSizeNeeded) { TCHAR empty[] = _T(""), prefix [] = _T("zar"); - TCHAR* buf = NULL; - CZipString tempPath; - if (lpszPath) + CZipString tempPath = lpszPath; + if (tempPath.IsEmpty()) + tempPath = "/tmp"; + if (ZipPlatform::GetDeviceFreeSpace(tempPath) < uSizeNeeded) + return empty; + CZipPathComponent::AppendSeparator(tempPath); + tempPath += prefix; + tempPath += _T("XXXXXX"); + int handle = mkstemp(tempPath.GetBuffer(tempPath.GetLength())); + tempPath.ReleaseBuffer(); + if (handle != -1) { - // first try the user provided directory - tempPath = lpszPath; - if (ZipPlatform::GetDeviceFreeSpace(tempPath) < iSizeNeeded) - tempPath.Empty(); - else - { - CZipPathComponent::AppendSeparator(tempPath); - tempPath += prefix; - tempPath += _T("XXXXXX"); - TCHAR* c = mktemp(tempPath.GetBuffer(tempPath.GetLength())); - tempPath.ReleaseBuffer(); - if (c) - return tempPath; - else - tempPath.Empty(); - } - } - - - TCHAR* v = tempnam(tempPath, prefix); - tempPath = v; - free(v); - - if (!tempPath.IsEmpty()) - { - CZipPathComponent zpc(tempPath); - if (ZipPlatform::GetDeviceFreeSpace(zpc.GetFilePath()) < iSizeNeeded) - return empty; + close(handle); // we just create the file and open it later return tempPath; } - else - return empty; + else + return empty; } bool ZipPlatform::GetCurrentDirectory(CZipString& sz) @@ -121,8 +108,7 @@ bool ZipPlatform::GetCurrentDirectory(CZipString& sz) bool ZipPlatform::SetFileAttr(LPCTSTR lpFileName, DWORD uAttr) { - return chmod(lpFileName, uAttr >> 16) == 0; - + return chmod(lpFileName, uAttr) == 0; } bool ZipPlatform::GetFileAttr(LPCTSTR lpFileName, DWORD& uAttr) @@ -130,21 +116,34 @@ bool ZipPlatform::GetFileAttr(LPCTSTR lpFileName, DWORD& uAttr) struct stat sStats; if (stat(lpFileName, &sStats) == -1) return false; - uAttr = (sStats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_IFMT)) << 16; + uAttr = (sStats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO | S_IFMT)); return true; - - } +bool ZipPlatform::SetExeAttr(LPCTSTR lpFileName) +{ + DWORD uAttr; + if (!GetFileAttr(lpFileName, uAttr)) + return false; + uAttr |= S_IXUSR; + return ZipPlatform::SetFileAttr(lpFileName, uAttr); +} + + bool ZipPlatform::GetFileModTime(LPCTSTR lpFileName, time_t & ttime) { - - struct stat st; + struct stat st; if (stat(lpFileName, &st) != 0) return false; ttime = st.st_mtime; - return ttime != -1; + if (ttime == (time_t)-1) + { + ttime = time(NULL); + return false; + } + else + return true; } bool ZipPlatform::SetFileModTime(LPCTSTR lpFileName, time_t ttime) @@ -172,9 +171,6 @@ int ZipPlatform::FileExists(LPCTSTR lpszName) else return 1; } - - - } ZIPINLINE bool ZipPlatform::IsDriveRemovable(LPCTSTR lpszFilePath) @@ -218,22 +214,22 @@ ZIPINLINE bool ZipPlatform::RenameFile( LPCTSTR lpszOldName, LPCTSTR lpszNewNam } ZIPINLINE bool ZipPlatform::IsDirectory(DWORD uAttr) { - return S_ISDIR(uAttr >> 16) != 0; + return S_ISDIR(uAttr) != 0; } -ZIPINLINE bool ZipPlatform::CreateDirectory(LPCTSTR lpDirectory) -{ - return mkdir(lpDirectory, S_IRUSR | S_IWUSR | S_IRGRP |S_IROTH) == 0; +ZIPINLINE bool ZipPlatform::CreateDirectory(LPCTSTR lpDirectory) +{ + return mkdir(lpDirectory, ZIP_DEFAULT_DIR_ATTRIBUTES) == 0; } ZIPINLINE DWORD ZipPlatform::GetDefaultAttributes() { - return 0x81a40000; + return S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; } ZIPINLINE DWORD ZipPlatform::GetDefaultDirAttributes() { - return 0x41ff0010; + return S_IFDIR | ZIP_DEFAULT_DIR_ATTRIBUTES; } @@ -248,15 +244,15 @@ ZIPINLINE bool ZipPlatform::GetSystemCaseSensitivity() } -bool ZipPlatform::TruncateFile(int iDes, DWORD iSize) +bool ZipPlatform::TruncateFile(int iDes, ULONGLONG uSize) { - return ftruncate(iDes, iSize) == 0; + return ftruncate(iDes, uSize) == 0; } int ZipPlatform::OpenFile(LPCTSTR lpszFileName, UINT iMode, int iShareMode) { - return open(lpszFileName, iMode, S_IRUSR | S_IWUSR | S_IRGRP |S_IROTH ); + return open(lpszFileName, iMode, S_IRUSR | S_IWUSR | S_IRGRP |S_IROTH ); } bool ZipPlatform::FlushFile(int iDes) @@ -264,10 +260,10 @@ bool ZipPlatform::FlushFile(int iDes) return fsync(iDes) == 0; } -int ZipPlatform::GetFileSystemHandle(int iDes) +intptr_t ZipPlatform::GetFileSystemHandle(int iDes) { return iDes; } - +#endif // ZIP_ARCHIVE_LNX diff --git a/harbour/contrib/hbziparch/ZipPlatform_win.cpp b/harbour/contrib/hbziparch/ZipPlatform_win.cpp index d67b3266e7..457df1e249 100644 --- a/harbour/contrib/hbziparch/ZipPlatform_win.cpp +++ b/harbour/contrib/hbziparch/ZipPlatform_win.cpp @@ -1,92 +1,78 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPlatform.cpp $ -// $Archive: /ZipArchive/ZipPlatform.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. +// +// For the licensing details refer to the License.txt file. // -// For the licensing details see the file License.txt +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// +#include "_platform.h" + +#ifdef ZIP_ARCHIVE_WIN + +#define ZIP_USES_SAFE_WINDOWS_API #include "stdafx.h" -#include "zipplatform.h" -#include "zipfileheader.h" -#include "zipexception.h" -#include "zipautobuffer.h" +#include "ZipPlatform.h" +#include "ZipFileHeader.h" +#include "ZipException.h" +#include "ZipAutoBuffer.h" #include -#if defined _MSC_VER && !defined __BORLANDC__ /*_MSC_VER may be defined in Borland after converting the VC project */ +#ifndef __BORLANDC__ #include #else + #ifndef _UTIMBUF_DEFINED + #define _utimbuf utimbuf + #define _UTIMBUF_DEFINED + #endif #include #endif +#ifndef INVALID_FILE_ATTRIBUTES + #define INVALID_FILE_ATTRIBUTES ((DWORD)-1) +#endif + #include #include -#include -#include "zippathcomponent.h" -#include "zipcompatibility.h" +#include +#include "ZipPathComponent.h" +#include "ZipCompatibility.h" const TCHAR CZipPathComponent::m_cSeparator = _T('\\'); -#if defined(__MINGW32__) -#define _UTIMBUF_DEFINED -#endif - - -#ifndef _UTIMBUF_DEFINED -#define _utimbuf utimbuf -#endif - -DWORD ZipPlatform::GetDeviceFreeSpace(LPCTSTR lpszPath) +ULONGLONG ZipPlatform::GetDeviceFreeSpace(LPCTSTR lpszPath) { - DWORD SectorsPerCluster, BytesPerSector, NumberOfFreeClusters, TotalNumberOfClusters; + ULONGLONG uFreeBytesToCaller = 0, uTotalBytes = 0, uFreeBytes = 0; + CZipPathComponent zpc (lpszPath); CZipString szDrive = zpc.GetFileDrive(); - if (!GetDiskFreeSpace( + + if (!GetDiskFreeSpaceEx( szDrive, - &SectorsPerCluster, - &BytesPerSector, - &NumberOfFreeClusters, - &TotalNumberOfClusters)) + (PULARGE_INTEGER)&uFreeBytesToCaller, + (PULARGE_INTEGER)&uTotalBytes, + (PULARGE_INTEGER)&uFreeBytes)) + { CZipPathComponent::AppendSeparator(szDrive); // in spite of what is written in MSDN it is sometimes needed (on fixed disks) - if (!GetDiskFreeSpace( + if (!GetDiskFreeSpaceEx( szDrive, - &SectorsPerCluster, - &BytesPerSector, - &NumberOfFreeClusters, - &TotalNumberOfClusters)) - + (PULARGE_INTEGER)&uFreeBytesToCaller, + (PULARGE_INTEGER)&uTotalBytes, + (PULARGE_INTEGER)&uFreeBytes)) return 0; } - __int64 total = SectorsPerCluster * BytesPerSector * NumberOfFreeClusters; - return (DWORD)total; + return uFreeBytes; } -bool ZipPlatform::GetFileSize(LPCTSTR lpszFileName, DWORD& dSize) -{ - HANDLE f = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, 0, NULL); - if (!f) - return false; - DWORD dwSize; - dwSize = ::GetFileSize(f, NULL); - CloseHandle(f); - if (dwSize == 0xFFFFFFFF) - return false; - dSize = dwSize; - return true; -} - -CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, DWORD iSizeNeeded) +CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, ZIP_SIZE_TYPE uSizeNeeded) { TCHAR empty[] = _T(""); CZipString tempPath; @@ -94,26 +80,26 @@ CZipString ZipPlatform::GetTmpFileName(LPCTSTR lpszPath, DWORD iSizeNeeded) if (lpszPath) { tempPath = lpszPath; - bCheckTemp = GetDeviceFreeSpace(tempPath) < iSizeNeeded; + bCheckTemp = GetDeviceFreeSpace(tempPath) < uSizeNeeded; } if (bCheckTemp) { - DWORD size = GetTempPath(0, NULL); + DWORD size = GetTempPath(0, empty); if (size == 0) - return empty; - + return (CZipString)empty; + GetTempPath(size, tempPath.GetBuffer(size)); tempPath.ReleaseBuffer(); - if (GetDeviceFreeSpace(tempPath) < iSizeNeeded) + if (GetDeviceFreeSpace(tempPath) < uSizeNeeded) { - if (!GetCurrentDirectory(tempPath) || GetDeviceFreeSpace(tempPath) < iSizeNeeded) - return empty; + if (!GetCurrentDirectory(tempPath) || GetDeviceFreeSpace(tempPath) < uSizeNeeded) + return (CZipString)empty; } } CZipString tempName; if (!GetTempFileName(tempPath, _T("ZAR"), 0, tempName.GetBuffer(_MAX_PATH))) - return empty; + return (CZipString)empty; tempName.ReleaseBuffer(); return tempName; } @@ -143,16 +129,16 @@ bool ZipPlatform::GetFileAttr(LPCTSTR lpFileName, DWORD& uAttr) { // not using MFC due to MFC bug (attr is one byte there) DWORD temp = ::GetFileAttributes(lpFileName); - if (temp == ( DWORD )-1) + if (temp == INVALID_FILE_ATTRIBUTES) return false; uAttr = temp; return true; - + } bool ZipPlatform::GetFileModTime(LPCTSTR lpFileName, time_t & ttime) { -#if defined _MSC_VER && !defined __BORLANDC__ /*_MSC_VER may be defined in Borland after converting the VC project */ +#ifndef __BORLANDC__ struct _stat st; if (_tstat(lpFileName, &st) != 0) #else @@ -160,9 +146,14 @@ bool ZipPlatform::GetFileModTime(LPCTSTR lpFileName, time_t & ttime) if (stat(lpFileName, &st) != 0) #endif return false; - ttime = st.st_mtime; - return ttime != -1; + if (ttime == (time_t)-1) + { + ttime = time(NULL); + return false; + } + else + return true; } bool ZipPlatform::SetFileModTime(LPCTSTR lpFileName, time_t ttime) @@ -173,17 +164,25 @@ bool ZipPlatform::SetFileModTime(LPCTSTR lpFileName, time_t ttime) return _tutime(lpFileName, &ub) == 0; } - bool ZipPlatform::ChangeDirectory(LPCTSTR lpDirectory) { return _tchdir(lpDirectory) == 0; // returns 0 if ok } + int ZipPlatform::FileExists(LPCTSTR lpszName) { -#if defined(__BORLANDC__) - if (_access(lpszName, 0) == 0) +#ifndef __BORLANDC__ + #if _MSC_VER >= 1400 + if (_taccess_s(lpszName, 0) == 0) + #else + if (_taccess(lpszName, 0) == 0) + #endif #else - if (_taccess(lpszName, 0) == 0) + #ifdef _UNICODE + if (_waccess(lpszName, 0) == 0) + #else + if (access(lpszName, 0) == 0) + #endif #endif { if (DirectoryExists(lpszName)) @@ -211,40 +210,72 @@ ZIPINLINE bool ZipPlatform::SetVolLabel(LPCTSTR lpszPath, LPCTSTR lpszLabel) ZIPINLINE void ZipPlatform::AnsiOem(CZipAutoBuffer& buffer, bool bAnsiToOem) { +#ifdef ZIP_USES_SAFE_WINDOWS_API + UINT cpIn, cpOut; + if (bAnsiToOem) + { + cpIn = CP_ACP; + cpOut = CP_OEMCP; + } + else + { + cpIn = CP_OEMCP; + cpOut = CP_ACP; + } + + CZipAutoBuffer interBuffer; + + int size = buffer.GetSize(); + // iLen doesn't include terminating character + int iLen = MultiByteToWideChar(cpIn, MB_PRECOMPOSED, buffer, size, NULL, 0); + if (iLen <= 0) + return; + interBuffer.Allocate(iLen * sizeof(wchar_t)); + LPWSTR lpszWide = (LPWSTR)(char*)interBuffer; + iLen = MultiByteToWideChar(cpIn, MB_PRECOMPOSED, buffer, size, lpszWide, iLen); + ASSERT(iLen != 0); + + // iLen does not include terminating character + size = WideCharToMultiByte(cpOut, 0, lpszWide, iLen, NULL, 0, NULL, NULL); + if (size <= 0) + return; + buffer.Allocate(size); + size = WideCharToMultiByte(cpOut, 0, lpszWide, iLen, buffer, size, NULL, NULL); + ASSERT(size != 0); +#else if (bAnsiToOem) CharToOemBuffA(buffer, buffer, buffer.GetSize()); else OemToCharBuffA(buffer, buffer, buffer.GetSize()); +#endif } ZIPINLINE bool ZipPlatform::RemoveFile(LPCTSTR lpszFileName, bool bThrow) { if (!::DeleteFile((LPTSTR)lpszFileName)) - { if (bThrow) CZipException::Throw(CZipException::notRemoved, lpszFileName); - else + else return false; - } return true; } ZIPINLINE bool ZipPlatform::RenameFile( LPCTSTR lpszOldName, LPCTSTR lpszNewName, bool bThrow) { if (!::MoveFile((LPTSTR)lpszOldName, (LPTSTR)lpszNewName)) - { if (bThrow) CZipException::Throw(CZipException::notRenamed, lpszOldName); - else + else return false; - } return true; } + ZIPINLINE bool ZipPlatform::IsDirectory(DWORD uAttr) { return (uAttr & FILE_ATTRIBUTE_DIRECTORY) != 0; } + ZIPINLINE bool ZipPlatform::CreateDirectory(LPCTSTR lpDirectory) { return ::CreateDirectory(lpDirectory, NULL) != 0; @@ -252,12 +283,12 @@ ZIPINLINE bool ZipPlatform::CreateDirectory(LPCTSTR lpDirectory) ZIPINLINE DWORD ZipPlatform::GetDefaultAttributes() { - return 0x81a40020; // make it readable under Unix + return FILE_ATTRIBUTE_ARCHIVE; } ZIPINLINE DWORD ZipPlatform::GetDefaultDirAttributes() { - return 0x41ff0010; // make it readable under Unix + return FILE_ATTRIBUTE_DIRECTORY; } ZIPINLINE int ZipPlatform::GetSystemID() @@ -270,66 +301,95 @@ ZIPINLINE bool ZipPlatform::GetSystemCaseSensitivity() return false; } -#ifdef _UNICODE -int ZipPlatform::WideToSingle(LPCTSTR lpWide, CZipAutoBuffer &szSingle) +#ifdef _UNICODE +int ZipPlatform::WideToMultiByte(LPCWSTR lpszIn, CZipAutoBuffer &szOut, UINT uCodePage) { - size_t wideLen = wcslen(lpWide); + size_t wideLen = wcslen(lpszIn); if (wideLen == 0) { - szSingle.Release(); + szOut.Release(); return 0; } // iLen does not include terminating character - int iLen = WideCharToMultiByte(CP_ACP,0, lpWide, wideLen, szSingle, + int iLen = WideCharToMultiByte(uCodePage, 0, lpszIn, (int)wideLen, szOut, 0, NULL, NULL); if (iLen > 0) { - szSingle.Allocate(iLen, true); - iLen = WideCharToMultiByte(CP_ACP,0, lpWide , wideLen, szSingle, + szOut.Allocate(iLen, true); + iLen = WideCharToMultiByte(uCodePage, 0, lpszIn , (int)wideLen, szOut, iLen, NULL, NULL); ASSERT(iLen != 0); } else // here it means error { - szSingle.Release(); + szOut.Release(); iLen --; } return iLen; } -int ZipPlatform::SingleToWide(const CZipAutoBuffer &szSingle, CZipString& szWide) +int ZipPlatform::MultiByteToWide(const CZipAutoBuffer &szIn, CZipString& szOut, UINT uCodePage) { - int singleLen = szSingle.GetSize(); - // iLen doesn't include terminating character - int iLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSingle.GetBuffer(), singleLen, NULL, 0); + int singleLen = szIn.GetSize(); + // iLen doesn't include terminating character + DWORD dwFlags = uCodePage <= CP_OEMCP ? MB_PRECOMPOSED : 0; + int iLen = MultiByteToWideChar(uCodePage, dwFlags, szIn.GetBuffer(), singleLen, NULL, 0); if (iLen > 0) { - iLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSingle.GetBuffer(), singleLen, - szWide.GetBuffer(iLen) , iLen); - szWide.ReleaseBuffer(iLen); + iLen = MultiByteToWideChar(uCodePage, dwFlags, szIn.GetBuffer(), singleLen, + szOut.GetBuffer(iLen) , iLen); + szOut.ReleaseBuffer(iLen); ASSERT(iLen != 0); } else { - szWide.Empty(); + szOut.Empty(); iLen --; // return -1 } return iLen; - } #endif -#ifndef _MFC_VER +#if defined ZIP_ARCHIVE_STL || defined ZIP_FILE_USES_STL + +#if _MSC_VER > 1000 + #pragma warning( push ) + #pragma warning (disable : 4702) // unreachable code +#endif + + #include #include -bool ZipPlatform::TruncateFile(int iDes, DWORD iSize) -{ - int ret = chsize(iDes, iSize); - return ret != -1; +bool ZipPlatform::TruncateFile(int iDes, ULONGLONG uSize) +{ +#if (_MSC_VER >= 1400) + return _chsize_s(iDes, uSize) == 0; +#else + if (uSize <= LONG_MAX) + return chsize(iDes, (LONG)uSize) == 0; + else if (uSize > _I64_MAX) + CZipException::Throw(CZipException::tooBigSize); + else + { + HANDLE handle = (HANDLE)GetFileSystemHandle(iDes); + ULARGE_INTEGER li; + li.QuadPart = uSize; + li.LowPart = SetFilePointer(handle, li.LowPart, (LONG*)&li.HighPart, FILE_BEGIN); + if (li.LowPart == UINT_MAX && GetLastError() != NO_ERROR) + return false; + return SetEndOfFile(handle) != 0; + } + return false; // for the compiler +#endif } +#if _MSC_VER > 1000 + #pragma warning( pop ) +#endif + + int ZipPlatform::OpenFile(LPCTSTR lpszFileName, UINT iMode, int iShareMode) { switch (iShareMode) @@ -346,7 +406,16 @@ int ZipPlatform::OpenFile(LPCTSTR lpszFileName, UINT iMode, int iShareMode) default: iShareMode = SH_DENYNO; } +#if _MSC_VER >= 1400 + int handle; + if (_tsopen_s(&handle, lpszFileName, iMode, iShareMode, S_IREAD | S_IWRITE /*required only when O_CREAT mode*/) != 0) + return -1; + else + return handle; +#else return _tsopen(lpszFileName, iMode, iShareMode, S_IREAD | S_IWRITE /*required only when O_CREAT mode*/); +#endif + } bool ZipPlatform::FlushFile(int iDes) @@ -354,10 +423,12 @@ bool ZipPlatform::FlushFile(int iDes) return _commit(iDes) == 0; } -int ZipPlatform::GetFileSystemHandle(int iDes) +intptr_t ZipPlatform::GetFileSystemHandle(int iDes) { return _get_osfhandle(iDes); } -#endif //_MFC_VER +#endif // ZIP_ARCHIVE_STL + +#endif // ZIP_ARCHIVE_WIN diff --git a/harbour/contrib/hbziparch/ZipString.cpp b/harbour/contrib/hbziparch/ZipString.cpp index e7c3b38f70..2f29616c66 100644 --- a/harbour/contrib/hbziparch/ZipString.cpp +++ b/harbour/contrib/hbziparch/ZipString.cpp @@ -1,20 +1,19 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipString.cpp $ -// $Archive: /ZipArchive/ZipString.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. // -// For the licensing details see the file License.txt +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// -#include "zipstring.h" +#include "stdafx.h" +#include "ZipString.h" ZIPSTRINGCOMPARE GetCZipStrCompFunc(bool bCaseSensitive, bool bCollate) { diff --git a/harbour/contrib/hbziparch/common.mak b/harbour/contrib/hbziparch/common.mak index ed932c4939..80532ea684 100644 --- a/harbour/contrib/hbziparch/common.mak +++ b/harbour/contrib/hbziparch/common.mak @@ -13,20 +13,38 @@ LIB_OBJS = \ $(OBJ_DIR)hbzipnew$(OBJEXT) \ $(OBJ_DIR)hbzipcom$(OBJEXT) \ \ - $(OBJ_DIR)ziparchive$(OBJEXT) \ - $(OBJ_DIR)ZipPlatform_win$(OBJEXT) \ - $(OBJ_DIR)zipstorage$(OBJEXT) \ - $(OBJ_DIR)zipstring$(OBJEXT) \ - $(OBJ_DIR)zipplatformcomm$(OBJEXT) \ + $(OBJ_DIR)Aes$(OBJEXT) \ + $(OBJ_DIR)BaseLibCompressor$(OBJEXT) \ + $(OBJ_DIR)Bzip2Compressor$(OBJEXT) \ + $(OBJ_DIR)DeflateCompressor$(OBJEXT) \ + $(OBJ_DIR)DirEnumerator$(OBJEXT) \ + $(OBJ_DIR)FileFilter$(OBJEXT) \ + $(OBJ_DIR)Hmac$(OBJEXT) \ + $(OBJ_DIR)RandomPool$(OBJEXT) \ + $(OBJ_DIR)Sha1$(OBJEXT) \ + $(OBJ_DIR)Wildcard$(OBJEXT) \ + $(OBJ_DIR)ZipAesCryptograph$(OBJEXT) \ + $(OBJ_DIR)ZipArchive$(OBJEXT) \ + $(OBJ_DIR)ZipAutoBuffer$(OBJEXT) \ + $(OBJ_DIR)ZipCentralDir$(OBJEXT) \ + $(OBJ_DIR)ZipCompatibility$(OBJEXT) \ + $(OBJ_DIR)ZipCompressor$(OBJEXT) \ + $(OBJ_DIR)ZipCrc32Cryptograph$(OBJEXT) \ + $(OBJ_DIR)ZipCryptograph$(OBJEXT) \ + $(OBJ_DIR)ZipException$(OBJEXT) \ + $(OBJ_DIR)ZipExtraData$(OBJEXT) \ + $(OBJ_DIR)ZipExtraField$(OBJEXT) \ +# $(OBJ_DIR)ZipFile_mfc$(OBJEXT) \ + $(OBJ_DIR)ZipFile_stl$(OBJEXT) \ + $(OBJ_DIR)ZipFileHeader$(OBJEXT) \ + $(OBJ_DIR)ZipMemFile$(OBJEXT) \ +# $(OBJ_DIR)ZipPathComponent_lnx$(OBJEXT) \ $(OBJ_DIR)ZipPathComponent_win$(OBJEXT) \ - $(OBJ_DIR)zipmemfile$(OBJEXT) \ - $(OBJ_DIR)zipfileheader$(OBJEXT) \ - $(OBJ_DIR)zipfile$(OBJEXT) \ - $(OBJ_DIR)zipexception$(OBJEXT) \ - $(OBJ_DIR)zipcompatibility$(OBJEXT) \ - $(OBJ_DIR)zipcentraldir$(OBJEXT) \ - $(OBJ_DIR)zipautobuffer$(OBJEXT) \ - $(OBJ_DIR)stdafx$(OBJEXT) \ +# $(OBJ_DIR)ZipPlatform_lnx$(OBJEXT) \ + $(OBJ_DIR)ZipPlatform_win$(OBJEXT) \ + $(OBJ_DIR)ZipPlatformComm$(OBJEXT) \ + $(OBJ_DIR)ZipStorage$(OBJEXT) \ + $(OBJ_DIR)ZipString$(OBJEXT) \ all: \ $(LIB_PATH) \ diff --git a/harbour/contrib/hbziparch/hbcomprs.c b/harbour/contrib/hbziparch/hbcomprs.c index 3a22f9d93f..fb7f748081 100644 --- a/harbour/contrib/hbziparch/hbcomprs.c +++ b/harbour/contrib/hbziparch/hbcomprs.c @@ -79,10 +79,10 @@ static void hb_fsGrabDirectory( PHB_ITEM pDir, const char * szDirSpec, USHORT ui char buffer[ 32 ]; hb_arrayNew( pSubarray, 5 ); - if ( bFullPath ) + if( bFullPath ) { - char *szFullName = hb_xstrcpy(NULL,fDirSpec->szPath?fDirSpec->szPath:"",ffind->szName,NULL); - hb_itemPutC( hb_arrayGetItemPtr( pSubarray, F_NAME), szFullName ); + char * szFullName = hb_xstrcpy( NULL, fDirSpec->szPath ? fDirSpec->szPath : "", ffind->szName, NULL ); + hb_itemPutC( hb_arrayGetItemPtr( pSubarray, F_NAME ), szFullName ); hb_xfree( szFullName ); } else @@ -100,15 +100,16 @@ static void hb_fsGrabDirectory( PHB_ITEM pDir, const char * szDirSpec, USHORT ui while( hb_fsFindNext( ffind ) ); hb_itemRelease( pSubarray ); + hb_fsFindClose( ffind ); } } -void HB_EXPORT hb_fsDirectory( PHB_ITEM pDir, char* szSkleton, char* szAttributes, BOOL bDirOnly, BOOL bFullPath ) +void HB_EXPORT hb_fsDirectory( PHB_ITEM pDir, char * szSkleton, char * szAttributes, BOOL bDirOnly, BOOL bFullPath ) { USHORT uiMask; USHORT uiMaskNoLabel; - BYTE *szDirSpec; + BYTE * szDirSpec; /* #if defined(__MINGW32__) || ( defined(_MSC_VER) && _MSC_VER >= 910 ) @@ -138,7 +139,7 @@ void HB_EXPORT hb_fsDirectory( PHB_ITEM pDir, char* szSkleton, char* szAttribute hb_arrayNew( pDir, 0 ); - if ( bDirOnly ) + if( bDirOnly ) szAttributes = "D"; if( szAttributes && strlen( szAttributes ) > 0 ) @@ -153,28 +154,28 @@ void HB_EXPORT hb_fsDirectory( PHB_ITEM pDir, char* szSkleton, char* szAttribute if ( szSkleton && strlen( szSkleton ) > 0 ) szDirSpec = hb_fsNameConv( ( BYTE * ) szSkleton, &bAlloc ); else - szDirSpec = (BYTE *) OS_FILE_MASK; + szDirSpec = ( BYTE * ) OS_FILE_MASK; if( bDirOnly || bFullPath ) { - if ( ( pDirSpec = hb_fsFNameSplit( (char*) szDirSpec ) ) !=NULL ) + if ( ( pDirSpec = hb_fsFNameSplit( ( char * ) szDirSpec ) ) !=NULL ) { if( pDirSpec->szDrive ) - hb_fsChDrv( (BYTE) ( pDirSpec->szDrive[0] - 'A' ) ); + hb_fsChDrv( ( BYTE ) ( pDirSpec->szDrive[ 0 ] - 'A' ) ); if( pDirSpec->szPath ) - hb_fsChDir( (BYTE *) pDirSpec->szPath ); + hb_fsChDir( ( BYTE * ) pDirSpec->szPath ); } } /* Get the file list */ - hb_fsGrabDirectory( pDir, (const char*) szDirSpec, uiMask, pDirSpec, bFullPath, bDirOnly ); + hb_fsGrabDirectory( pDir, ( const char * ) szDirSpec, uiMask, pDirSpec, bFullPath, bDirOnly ); - if ( uiMask == HB_FA_LABEL ) + if( uiMask == HB_FA_LABEL ) { uiMaskNoLabel |= hb_fsAttrEncode( szAttributes ); uiMaskNoLabel &= ~HB_FA_LABEL; - hb_fsGrabDirectory( pDir, (const char*) szDirSpec, uiMaskNoLabel, pDirSpec, bFullPath, bDirOnly ); + hb_fsGrabDirectory( pDir, ( const char * ) szDirSpec, uiMaskNoLabel, pDirSpec, bFullPath, bDirOnly ); } if( pDirSpec ) diff --git a/harbour/contrib/hbziparch/hbziparc.c b/harbour/contrib/hbziparch/hbziparc.c index 7bc06f35fe..ad69f8200f 100644 --- a/harbour/contrib/hbziparch/hbziparc.c +++ b/harbour/contrib/hbziparch/hbziparc.c @@ -89,12 +89,12 @@ static int GetFileAttributes( char * szEntry ) { struct stat sStat; stat( szEntry, &sStat ); - return (int) sStat.st_mode; + return ( int ) sStat.st_mode; } static void SetFileAttributes( char * szEntry, ULONG ulAttr) { - chmod(szEntry,ulAttr); + chmod( szEntry, ulAttr ); } #endif @@ -634,7 +634,7 @@ HB_FUNC( HB_GETFILECOUNT ) if( ISCHAR( 1 ) ) { char szFile[ _POSIX_PATH_MAX ]; - char *szZipFileName; + char * szZipFileName; hb_strncpy( szFile, hb_parc( 1 ), sizeof( szFile ) - 1 ); @@ -1072,18 +1072,17 @@ HB_FUNC( HB_UNZIPFILE ) char *szZipFileName; BYTE *pCurDir; - pCurDir = ( BYTE * )hb_xstrcpy( NULL, OS_PATH_DELIMITER_STRING, ( const char * )hb_fsCurDir( 0 ) , NULL ); + pCurDir = ( BYTE * ) hb_xstrcpy( NULL, OS_PATH_DELIMITER_STRING, ( const char * ) hb_fsCurDir( 0 ) , NULL ); hb_strncpy( szFile, hb_parc( 1 ), sizeof( szFile ) - 1 ); szZipFileName = hb___CheckFile( szFile ); - s_UnzipFiles = hb_itemArrayNew(0); + s_UnzipFiles = hb_itemArrayNew( 0 ); - if( hb_TestForPKS( szZipFileName ) <=0 ) + if( hb_TestForPKS( szZipFileName ) <= 0 ) { - hb___GetFileNamesFromZip( szZipFileName, TRUE ); - + hb___GetFileNamesFromZip( szZipFileName, TRUE ); if( pUnzip ) { @@ -1113,6 +1112,7 @@ HB_FUNC( HB_UNZIPFILE ) //s.r. change "*.*" to "*" because file without extension were ignored UnzipCreateArray( (char*) "*", 1 ); } + if ( hb_arrayLen(s_UnzipFiles) > 0 ) { PHB_ITEM pProgress = ISBLOCK( 7 ) ? hb_itemNew( hb_param( 7 , HB_IT_BLOCK ) ) : hb_itemNew( NULL ); @@ -1276,7 +1276,6 @@ HB_FUNC( HB_ZIPDELETEFILES ) int iIndex = hb_itemGetNI( pDelZip ); PHB_ITEM Temp; - if( iIndex > 0 && iIndex <= ulLen ) { PHB_ITEM pZipEntry = hb_arrayGetItemPtr( hbza_ZipArray, iIndex ); @@ -1551,7 +1550,7 @@ HB_FUNC( HB_UNZIPFILEINDEX ) { PHB_ITEM pDelZip = hb_param( 6, HB_IT_NUMERIC | HB_IT_ARRAY ); - if ( pDelZip ) + if( pDelZip ) { char szFile[ _POSIX_PATH_MAX ]; PHB_ITEM Temp,DelZip; @@ -1566,11 +1565,11 @@ HB_FUNC( HB_UNZIPFILEINDEX ) hb___GetFileNamesFromZip( szZipFileName, TRUE ); ulLen = hb_arrayLen(hbza_ZipArray); - if ( HB_IS_NUMERIC ( pDelZip ) ) + if( HB_IS_NUMERIC( pDelZip ) ) { int iIndex = hb_itemGetNI( pDelZip ); - if ( iIndex > 0 && iIndex <= ulLen ) + if( iIndex > 0 && iIndex <= ulLen ) { Temp = hb_itemNew(NULL); hb_arrayAddForward( DelZip, hb_itemPutNI( Temp, iIndex ) ); @@ -1581,12 +1580,12 @@ HB_FUNC( HB_UNZIPFILEINDEX ) { int ui, iIndex; - for ( ui = 0 ; ui < ulLen; ui ++ ) + for( ui = 0 ; ui < ulLen; ui ++ ) { iIndex = hb_arrayGetNI( pDelZip, ui + 1 ); if ( iIndex && iIndex > 0 && iIndex <= ulLen ) { - Temp = hb_itemNew(NULL); + Temp = hb_itemNew( NULL ); hb_arrayAddForward( DelZip, hb_itemPutNI( Temp, iIndex ) ); hb_itemRelease( Temp ); } @@ -1594,7 +1593,7 @@ HB_FUNC( HB_UNZIPFILEINDEX ) } - if( hb_arrayLen(DelZip) > 0 ) + if( hb_arrayLen( DelZip ) > 0 ) { PHB_ITEM pProgress = ISBLOCK( 7 ) ? hb_itemNew( hb_param( 7 , HB_IT_BLOCK ) ) : hb_itemNew( NULL ); bRet = hb_UnzipSelIndex( szZipFileName, @@ -1652,9 +1651,9 @@ HB_FUNC(HB_UNZIPALLFILE) hb_strncpy( szFile, hb_parc( 1 ), sizeof( szFile ) - 1 ); szZipFile = hb___CheckFile(szFile); hb_retl( hb_UnzipAll( szZipFile, - hb_param( 2, HB_IT_BLOCK), + hb_param( 2, HB_IT_BLOCK ), ISLOG(3) ? hb_parl(3) : FALSE, - hb_parc(4), + hb_parc( 4 ), ISCHAR(5) ? hb_parc(5) : NULL, hb_param( 6, HB_IT_BLOCK ), pProgress ) ); diff --git a/harbour/contrib/hbziparch/hbzipcom.cpp b/harbour/contrib/hbziparch/hbzipcom.cpp index 7b456b5a47..58e7aa9641 100644 --- a/harbour/contrib/hbziparch/hbzipcom.cpp +++ b/harbour/contrib/hbziparch/hbzipcom.cpp @@ -58,27 +58,27 @@ extern "C" { #endif -class SpanCallbackc : public CZipSpanCallback +class SegmCallbackc : public CZipSegmCallback { - bool Callback( int iProgress ) + bool Callback( ZIP_SIZE_TYPE iProgress ) { - PHB_ITEM Disk=hb_itemPutNL( NULL, m_uDiskNeeded ); + PHB_ITEM Disk=hb_itemPutNL( NULL, m_uVolumeNeeded ); - hb_vmEvalBlockV( hbza_ChangeDiskBlock, 1, Disk ); + hb_vmEvalBlockV( hbza_ChangeDiskBlock, 1, Disk ); hb_itemRelease( Disk ); return TRUE; } }; -class SpanActionCallbackc : public CZipActionCallback +class SegmActionCallbackc : public CZipActionCallback { - bool Callback( int iProgress ) + bool Callback( ZIP_SIZE_TYPE iProgress ) { - PHB_ITEM Disk = hb_itemPutNL( NULL, m_uTotalSoFar ); - PHB_ITEM Total = hb_itemPutNL( NULL, m_uTotalToDo ); + PHB_ITEM Disk = hb_itemPutNL( NULL, m_uProcessed ); + PHB_ITEM Total = hb_itemPutNL( NULL, m_uTotalToProcess ); - hb_vmEvalBlockV( hbza_pProgressInfo, 2, Disk,Total); + hb_vmEvalBlockV( hbza_pProgressInfo, 2, Disk, Total ); hb_itemRelease( Disk ); hb_itemRelease( Total ); @@ -101,9 +101,14 @@ static DWORD hb_GetCurrentFileSize( LPCTSTR szFile ) if ( dwFlags & hFilesFind.dwFileAttributes ) { if( hFilesFind.nFileSizeHigh>0 ) + { return ( ( hFilesFind.nFileSizeHigh*MAXDWORD )+hFilesFind.nFileSizeLow ); + } else + { return ( hFilesFind.nFileSizeLow ); + } + } } @@ -122,22 +127,22 @@ static DWORD hb_GetCurrentFileSize( LPCTSTR szFile ) int hb_CompressFile( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock, BOOL bOverWrite, char *szPassWord, BOOL bPath, BOOL bDrive, PHB_ITEM pProgress ) { ULONG ulCount; - const char *szDummy ; - char *szDummyLower ; - char *szFileLower = hb_strdup((char *)szFile) ; - BOOL bFileExist = hb_fsFile( ( BYTE* )szFile ); + const char *szDummy; + char *szDummyLower; + char *szFileLower = hb_strdup( ( char * ) szFile ); + BOOL bFileExist = hb_fsFile( ( BYTE* ) szFile ); BOOL bAdded; - BOOL bReturn = TRUE; + BOOL bReturn = TRUE; DWORD dwSize; CZipArchive szZip; - SpanCallbackc span; - SpanActionCallbackc spanac; + SegmCallbackc span; + SegmActionCallbackc spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); #ifdef HB_OS_WIN_32 - hb_strLower( szFileLower, strlen( szFileLower )) ; + hb_strLower( szFileLower, strlen( szFileLower )) ; #endif try @@ -157,8 +162,10 @@ int hb_CompressFile( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBl if ( bReturn ) { - if( szPassWord ) + if ( szPassWord != NULL ) + { szZip.SetPassword( szPassWord ); + } if ( hbza_pZipI.szComment != NULL ) { @@ -203,9 +210,14 @@ int hb_CompressFile( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBl try { if ( bPath && !bAdded ) + { szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ); + // bAdded = TRUE; + } else if ( !bDrive && !bPath && !bAdded ) + { szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ); + } } catch( ... ){} @@ -215,11 +227,11 @@ int hb_CompressFile( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBl } } hb_xfree( szFileLower ) ; - try { szZip.Close( ); } + catch ( CZipException ) { bReturn = FALSE; @@ -240,19 +252,22 @@ int hb_CmpTdSpan( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock BOOL bFileExist = hb_fsFile( ( BYTE* )szFile ); CZipArchive szZip; - SpanCallbackc span; - SpanActionCallbackc spanac; + SegmCallbackc span; + SegmActionCallbackc spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); - if( iSpanSize == 0 ) + + if ( iSpanSize == 0 ) + { iSpanSize = 1457664; + } try { if( ( bFileExist && bOverWrite ) || !bFileExist ) { - szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize ); + szZip.Open( szFile, CZipArchive::zipCreateSegm, iSpanSize ); } else { @@ -271,8 +286,10 @@ int hb_CmpTdSpan( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock //if (! bReturn ) //{ - if( szPassWord ) + if ( szPassWord != NULL ) + { szZip.SetPassword( szPassWord ); + } if ( hbza_pZipI.szComment != NULL ) { @@ -307,10 +324,17 @@ int hb_CmpTdSpan( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock try { + if ( bPath && !bAdded ) + { szZip.AddNewFile( szDummy, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ); + // bAdded = TRUE; + } else if ( !bDrive && !bPath && !bAdded ) + { szZip.AddNewFile( szDummy, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ); + } + } catch( ... ){} } @@ -321,6 +345,7 @@ int hb_CmpTdSpan( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock { szZip.Close(); } + catch ( CZipException ) { bReturn = FALSE; @@ -340,18 +365,23 @@ int hb_CompressFileStd( char *szFile, char *szFiletoCompress, int iCompLevel, PH BOOL bAdded = FALSE; CZipArchive szZip; - SpanCallbackc span; - SpanActionCallbackc spanac; + SegmCallbackc span; + SegmActionCallbackc spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); try { if( ( bFileExist && bOverWrite ) || !bFileExist ) + { szZip.Open( szFile, CZipArchive::zipCreate, 0 ); + } else + { szZip.Open( szFile, CZipArchive::zipOpen, 0 ); + } } + catch ( CZipException ) { bReturn = FALSE; @@ -359,8 +389,10 @@ int hb_CompressFileStd( char *szFile, char *szFiletoCompress, int iCompLevel, PH if ( bReturn ) { - if( szPassWord ) + if ( szPassWord != NULL ) + { szZip.SetPassword( szPassWord ); + } if ( hbza_pZipI.szComment != NULL ) { @@ -388,12 +420,14 @@ int hb_CompressFileStd( char *szFile, char *szFiletoCompress, int iCompLevel, PH hb_vmEvalBlockV( pBlock, 1, FileName); hb_itemRelease( FileName ); + } #if ( defined( __WIN32__ ) || defined( __MINGW32__ ) ) && defined( HB_USE_DRIVE_ADD ) if ( bDrive && !bAdded ) { - if (! szZip.AddNewFileDrv( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) ) + /* NOTE: Was AddNewFileDrv() */ + if (! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) ) { bReturn = FALSE; } @@ -407,22 +441,32 @@ int hb_CompressFileStd( char *szFile, char *szFiletoCompress, int iCompLevel, PH if ( bPath && !bAdded ) { if( ! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 )) + { bReturn = FALSE; + } + else + { + // bAdded = TRUE; + } } else if ( !bDrive && !bPath && !bAdded ) { if (! szZip.AddNewFile( szFiletoCompress, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 )) + { bReturn = FALSE; + } } + + } } catch( ... ){} } - try { szZip.Close( ); } + catch ( CZipException ) { bReturn = FALSE; @@ -440,21 +484,29 @@ int hb_CmpTdSpanStd( char *szFile, char * szFiletoCompress, int iCompLevel, PHB_ BOOL bFileExist = hb_fsFile( ( BYTE* )szFile ); CZipArchive szZip; - SpanCallbackc span; - SpanActionCallbackc spanac; + SegmCallbackc span; + SegmActionCallbackc spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); - if( iSpanSize == 0 ) + + if ( iSpanSize == 0 ) + { iSpanSize = 1457664; + } try { if( ( bFileExist && bOverWrite ) || !bFileExist ) - szZip.Open( szFile, CZipArchive::zipCreateSpan, iSpanSize ); + { + szZip.Open( szFile, CZipArchive::zipCreateSegm, iSpanSize ); + } else + { return ( int ) false; + } } + catch ( CZipException ) { bReturn = FALSE; @@ -462,8 +514,10 @@ int hb_CmpTdSpanStd( char *szFile, char * szFiletoCompress, int iCompLevel, PHB_ catch( ... ){} - if( szPassWord ) + if ( szPassWord != NULL ) + { szZip.SetPassword( szPassWord ); + } if ( hbza_pZipI.szComment != NULL ) { @@ -476,42 +530,57 @@ int hb_CmpTdSpanStd( char *szFile, char * szFiletoCompress, int iCompLevel, PHB_ hbza_pProgressInfo = pProgress; szZip.SetCallback( &spanac ); } - if ( bReturn ) { try { - if( szPassWord ) + if ( szPassWord != NULL ) + { szZip.SetPassword( szPassWord ); + } - if( pBlock ) + if( pBlock != NULL ) { PHB_ITEM FileName=hb_itemPutC( NULL, szFiletoCompress ) ; hb_vmEvalBlockV( pBlock, 1, FileName); hb_itemRelease( FileName ); + } #if defined( __WIN32__ ) || defined( __MINGW32__ ) if ( bDrive && !bAdded ) { - if (! szZip.AddNewFileDrv( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) ) + /* NOTE: Was AddNewFileDrv() */ + if (! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) ) + { bReturn = FALSE; + } else + { bAdded = TRUE; + } } #endif if ( bPath && !bAdded ) { if (! szZip.AddNewFile( szFiletoCompress, iCompLevel, true, CZipArchive::zipsmSafeSmart, 65536 ) ) + { bReturn = FALSE; + } + else + { + // bAdded = TRUE; + } } else if ( !bDrive && !bPath && !bAdded ) { if (! szZip.AddNewFile( szFiletoCompress, iCompLevel, false, CZipArchive::zipsmSafeSmart, 65536 ) ) + { bReturn = FALSE; + } } } diff --git a/harbour/contrib/hbziparch/hbzipnew.cpp b/harbour/contrib/hbziparch/hbzipnew.cpp index f4196a3a2d..abe64e6f9b 100644 --- a/harbour/contrib/hbziparch/hbzipnew.cpp +++ b/harbour/contrib/hbziparch/hbzipnew.cpp @@ -56,11 +56,11 @@ extern "C" { #endif -class SpanCallback : public CZipSpanCallback +class SegmCallback : public CZipSegmCallback { - bool Callback( int iProgress ) + bool Callback( ZIP_SIZE_TYPE iProgress ) { - PHB_ITEM Disk = hb_itemPutNL( NULL, m_uDiskNeeded ) ; + PHB_ITEM Disk = hb_itemPutNL( NULL, m_uVolumeNeeded ) ; hb_vmEvalBlockV( hbza_ChangeDiskBlock, 1, Disk); @@ -70,11 +70,12 @@ class SpanCallback : public CZipSpanCallback } }; -class SpanActionCallback : public CZipActionCallback +class SegmActionCallback : public CZipActionCallback { - bool Callback( int iProgress ) + bool Callback( ZIP_SIZE_TYPE iProgress ) { - PHB_ITEM Disk = hb_itemPutNL( NULL , m_uTotalSoFar ), Total= hb_itemPutNL( NULL, m_uTotalToDo ); + PHB_ITEM Disk = hb_itemPutNL( NULL , m_uProcessed ), Total= hb_itemPutNL( NULL, m_uTotalToProcess ); + hb_vmEvalBlockV( hbza_pProgressInfo, 2, Disk, Total); @@ -91,10 +92,10 @@ static int hb_CheckSpanMode( char * szFile ) int iReturn = 0; CZipArchive szZip; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); try { @@ -109,13 +110,13 @@ static int hb_CheckSpanMode( char * szFile ) { szZip.Close( true ); iReturn = 114; - } - else if ( e.m_iCause == CZipException::noCallback ) + } else if ( e.m_iCause == CZipException::noCallback ) { szZip.Close( true ); iReturn = 103; } - else if ( e.m_iCause == CZipException::generic ) + + else if ( e.m_iCause == CZipException::genericError ) { szZip.Close( true ); iReturn = 100; @@ -125,76 +126,106 @@ static int hb_CheckSpanMode( char * szFile ) szZip.Close( true ); iReturn = 101; } + + else if ( e.m_iCause == CZipException::badCrc ) { szZip.Close( true ); iReturn = 102; } + + + else if ( e.m_iCause == CZipException::aborted ) { szZip.Close( true ); iReturn = 104; } + + else if ( e.m_iCause == CZipException::abortedAction ) { szZip.Close( true ); iReturn = 105; } + + else if ( e.m_iCause == CZipException::abortedSafely ) { szZip.Close( true ); iReturn = 106; } + + else if ( e.m_iCause == CZipException::nonRemovable ) { szZip.Close( true ); iReturn = 107; } + + else if ( e.m_iCause == CZipException::tooManyVolumes ) { szZip.Close( true ); iReturn = 108; } - else if ( e.m_iCause == CZipException::tooLongFileName ) + + + else if ( e.m_iCause == CZipException::tooLongData ) { szZip.Close( true ); iReturn = 109; } + + else if ( e.m_iCause == CZipException::badPassword ) { szZip.Close( true ); iReturn = 110; } + + else if ( e.m_iCause == CZipException::dirWithSize ) { szZip.Close( true ); iReturn = 111; } - else if ( e.m_iCause == CZipException::internal ) + + + else if ( e.m_iCause == CZipException::internalError ) { szZip.Close( true ); iReturn = 112; } + + else if ( e.m_iCause == CZipException::notRemoved ) { szZip.Close( true ); iReturn = 113; } + + else if ( e.m_iCause == CZipException::notRenamed ) { szZip.Close( true ); iReturn = 114; } + + else if ( e.m_iCause == CZipException::platfNotSupp) { szZip.Close( true ); iReturn = 115; } - } + + + + } if ( ! iReturn ) { - iReturn = szZip.GetSpanMode( ); + iReturn = szZip.GetSegmMode( ); szZip.Close( ); } @@ -213,17 +244,17 @@ int hb_CmpPkSpan( char *szFile, PHB_ITEM pArray, int iCompLevel, PHB_ITEM pBlock CZipString szArchive = szFile; CZipArchive szZip; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); bDrive = false; try { if( ( bFileExist && bOverWrite ) || !bFileExist ) { - szZip.Open( szArchive, CZipArchive::zipCreateSpan, 0 ); + szZip.Open( szArchive, CZipArchive::zipCreateSegm, 0 ); } else { @@ -313,7 +344,7 @@ PHB_ITEM hb___GetFileNamesFromZip( char *szFile, BOOL iMode ) bool iReturn = true; CZipArchive szZip; - SpanCallback span; + SegmCallback span; if ( hbza_pZipI.iWrite > 0 ) { @@ -329,7 +360,7 @@ PHB_ITEM hb___GetFileNamesFromZip( char *szFile, BOOL iMode ) break; case -1: - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); break; @@ -521,7 +552,7 @@ BOOL hb_IsPassWord( char *szFile ) CZipFileHeader fh; CZipArchive szZip; - SpanCallback span; + SegmCallback span; try { @@ -532,7 +563,7 @@ BOOL hb_IsPassWord( char *szFile ) break; case -1: - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); break; @@ -563,9 +594,9 @@ int hb___GetNumberofFilestoUnzip( char *szFile ) int iNumberOfFiles; CZipArchive szZip; - SpanCallback span; + SegmCallback span; - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); try { szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); iNumberOfFiles = szZip.GetCount( ); @@ -650,7 +681,7 @@ int hb_DeleteSel( char *szFile, PHB_ITEM pArray, BOOL bCase ) aFiles.Add( szDummy ); } - szZip.DeleteFiles( aFiles ); + szZip.RemoveFiles( aFiles ); } szZip.Close( ); @@ -671,8 +702,8 @@ int hb_UnzipSel( char *szFile, PHB_ITEM pBlock, BOOL lWithPath, char *szPassWord LPCTSTR lpFiletoExtract; CZipArchive szZip; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; if ( HB_IS_BLOCK( pProgress ) ) { @@ -689,7 +720,7 @@ int hb_UnzipSel( char *szFile, PHB_ITEM pBlock, BOOL lWithPath, char *szPassWord break; case -1: - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); break; @@ -847,8 +878,8 @@ const char * hb_GetZipComment( char *szFile ) CZipString szTemp; CZipArchive szZip; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; try { @@ -859,7 +890,7 @@ const char * hb_GetZipComment( char *szFile ) break; case -1: - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); break; @@ -897,8 +928,8 @@ int hb_UnzipSelIndex( char *szFile, PHB_ITEM pBlock, BOOL lWithPath, char *szPas int iCause; CZipArchive szZip; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; if ( HB_IS_BLOCK( pProgress ) ) { @@ -915,7 +946,7 @@ int hb_UnzipSelIndex( char *szFile, PHB_ITEM pBlock, BOOL lWithPath, char *szPas break; case -1: - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open( szFile, hbza_pZipI.iReadOnly ? CZipArchive::zipOpenReadOnly : CZipArchive::zipOpen, 0 ); break; @@ -1064,8 +1095,8 @@ int hb_UnzipAll(char *szFile,PHB_ITEM pBlock, BOOL bWithPath,char *szPassWord,ch int iMode = true; CZipArchive szZip; BOOL bChange = FALSE; - SpanCallback span; - SpanActionCallback spanac; + SegmCallback span; + SegmActionCallback spanac; char * szPath = (char*) hb_xgrab( _POSIX_PATH_MAX + 1 ); BOOL bFreePath = TRUE; @@ -1091,7 +1122,7 @@ int hb_UnzipAll(char *szFile,PHB_ITEM pBlock, BOOL bWithPath,char *szPassWord,ch } else { if (iMode ==-1) { - szZip.SetSpanCallback( &span ); + szZip.SetSegmCallback( &span ); szZip.Open(szFile,CZipArchive::zipOpen,0); } else { diff --git a/harbour/contrib/hbziparch/make_gcc.sh b/harbour/contrib/hbziparch/make_gcc.sh index 216534f9b8..0593942308 100755 --- a/harbour/contrib/hbziparch/make_gcc.sh +++ b/harbour/contrib/hbziparch/make_gcc.sh @@ -4,6 +4,4 @@ # $Id$ # -export CFLAGS=-I./include ../mtpl_gcc.sh $1 $2 $3 $4 $5 $6 $7 $8 $9 -unset CFLAGS \ No newline at end of file diff --git a/harbour/contrib/hbziparch/make_vc.bat b/harbour/contrib/hbziparch/make_vc.bat index e79111853f..a644a30e22 100644 --- a/harbour/contrib/hbziparch/make_vc.bat +++ b/harbour/contrib/hbziparch/make_vc.bat @@ -3,7 +3,7 @@ rem rem $Id$ rem -set CFLAGS=-EHsc -D_CRT_NONSTDC_NO_DEPRECATE +set CFLAGS=-EHsc call ..\mtpl_vc.bat %1 %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/harbour/contrib/hbziparch/readme.txt b/harbour/contrib/hbziparch/readme.txt new file mode 100644 index 0000000000..0fd5e9833c --- /dev/null +++ b/harbour/contrib/hbziparch/readme.txt @@ -0,0 +1,73 @@ +/** \page pageLic Licensing information + +ZipArchive library - creation, modification and decompression of "zip" format archives
+Copyright © 2000 - 2002 Tadeusz Dracz.
+E-Mail: \htmlonly tdracz@artpol-software.com
+Web: http://www.artpol-software.com \endhtmlonly + +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 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 General Public License for more details. + +You should have received a copy of the GNU 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 + +
+************************************************************************* +An English version of the \ref pageGPL "GNU GPL" is in the gpl.txt file distributed with +this project. Translations to other languages are available at: +\htmlonly +http://www.gnu.org/copyleft/gpl.html +\endhtmlonly + + +Distributing ZipArchive under GNU GPL implies ZipArchive can only be used +with software that is licensed under conditions compliant with the GPL. +Embedding in proprietary software requires an alternative license. + + +\subsection s1 Alternative license for use with proprietary software + + +If you want to distribute software in a commercial context that incorporates +ZipArchive and you do not want to meet the conditions of GNU GPL +(e.g. an obligation to provide a customer with the source code of your +software that uses the ZipArchive library), you need to have a commercial license. +- The commercial license provides you with the same rights as the GNU GPL, but in +addition allows you to embed ZipArchive library in proprietary software without +affecting the copyright of this software (it removes the GNU GPL obligation +to publish the source code) +- The license gives you royalty free distribution rights +- The license does not allow you to transfer these rights +- The license is granted per developer +- You won't need to purchase an additional license for the future versions of the library + + +The commercial license is available free of charge for using ZipArchive library in: +- freeware software (freeware is software that is available free of charge, but which is copyrighted by the developer, who retains the right to control its redistribution and to sell it in the future) + - excluded is software which is associated with an equipment that the same company manufactures and which has no practical usage value without it (e.g. software used for maintenace of machines) - unless the equipment is free as well (?) + - if you decide to sell the software in the future - you will need to purchase the commercial license for using the ZipArchive library, unless it is distributed in the shareware way - see below +- software distributed in the Shareware way (Shareware distribution gives users a chance to try software before buying it. If you try a Shareware program and continue using it, you are expected to register. Individual programs differ on details -- some request registration while others require it, some specify a maximum trial period. +Copyright laws apply to both Shareware and commercial software and the copyright holder retains all rights, with the exception that copying and distributing the program for evaluation purposes is encouraged, subject to certain conditions. For example, some authors require written permission before a commercial disk vendor may copy their Shareware. ) + - excluded is software which price for a single copy is higher than the price of the ZipArchive library for a single developer + +Extended Licence for HBZLIB (library for zip compression in \htmlonly Harbour\endhtmlonly)
+You can create proprietary software using hbzlib respecting the follow: +- ZipArchive library must be linked together with hbzlib +- you cannot use ZipArchive as a dynamic library (DLL), it must be linked staticaly with the software +- the commercial license for ZipArchive is free of charge, but these grants are valid only if the whole application is written with Harbour + +There is a fee for the commercial license for using the library in the software not falling into the mentioned categories. +
+It is recommended that you should print two copies of the commercial license +document after you receive it, sign them and send by post. One copy, signed by the author will be sent back to you. +Please \htmlonly contact the author or visit the Artpol Software web site\endhtmlonly to find out more. + +*/ diff --git a/harbour/contrib/hbziparch/resource.h b/harbour/contrib/hbziparch/resource.h index 6cf0c78db2..d018c8ae88 100644 --- a/harbour/contrib/hbziparch/resource.h +++ b/harbour/contrib/hbziparch/resource.h @@ -1,6 +1,6 @@ //{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. -// Used by version.rc +// Used by ZipArchive.rc // // Next default values for new objects diff --git a/harbour/contrib/hbziparch/stdafx.cpp b/harbour/contrib/hbziparch/stdafx.cpp deleted file mode 100644 index 98e3f3d000..0000000000 --- a/harbour/contrib/hbziparch/stdafx.cpp +++ /dev/null @@ -1,20 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: stdafx.cpp $ -// $Archive: /ZipArchive/stdafx.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" - - diff --git a/harbour/contrib/hbziparch/stdafx.h b/harbour/contrib/hbziparch/stdafx.h index 3205563710..04d72ef29e 100644 --- a/harbour/contrib/hbziparch/stdafx.h +++ b/harbour/contrib/hbziparch/stdafx.h @@ -1,126 +1,84 @@ //////////////////////////////////////////////////////////////////////////////// -// $Workfile: stdafx.h $ -// $Archive: /ZipArchive_STL/stdafx.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// // This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) +// is Copyrighted 2000 - 2007 by Artpol Software - Tadeusz Dracz // // 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. // -// For the licensing details see the file License.txt +// For the licensing details refer to the License.txt file. +// +// Web Site: http://www.artpol-software.com //////////////////////////////////////////////////////////////////////////////// -#if !defined(AFX_STDAFX_H__926F70F4_1B34_49AA_9532_498E8D2F3495__INCLUDED_) -#define AFX_STDAFX_H__926F70F4_1B34_49AA_9532_498E8D2F3495__INCLUDED_ +/** +* \file stdafx.h +* Contains global definitions. +* +*/ -#if (_MSC_VER < 1300) && !defined (__BORLANDC__) && !defined (__GNUC__) +#if !defined(ZIPARCHIVE_STDAFX_DOT_H) +#define ZIPARCHIVE_STDAFX_DOT_H + +#include "_features.h" +#include "_platform.h" + +#if _MSC_VER > 1000 + #pragma once +#endif + +// uncomment to disable compiling standard error messages into the library +#define ZIP_ENABLE_ERROR_DESCRIPTION + + + +#if _MSC_VER < 1300 && !defined __BORLANDC__ && !defined (__GNUC__) #define ZIPINLINE inline #else #define ZIPINLINE #endif - -#define ZIP_ARCHIVE_STL - -#if _MSC_VER > 1000 - #pragma once -//because of STL - #pragma warning (disable : 4710) // 'function' : function not inlined - #pragma warning (disable : 4514) // unreferenced inline/local function has been removed - #pragma warning (disable:4786) // 'identifier' : identifier was truncated to 'number' characters in the debug information -#endif // _MSC_VER > 1000 - - -// some Windows typical definitions - -#if defined (_UNICODE) && !defined (UNICODE) - #define UNICODE -#endif -#if defined (UNICODE) && !defined (_UNICODE) - #define _UNICODE -#endif - -#ifndef _WIN32 - #ifndef NULL - #define NULL 0 - #endif - - #include - typedef int HFILE; - typedef void* HANDLE; - typedef unsigned long DWORD; - typedef long LONG; - typedef int BOOL; - typedef unsigned char BYTE; - typedef unsigned short WORD; - typedef unsigned int UINT; - - #ifndef FALSE - #define FALSE (int)0 - #endif - - #ifndef TRUE - #define TRUE (int)1 - #endif - - - typedef unsigned short WCHAR; // wc, 16-bit UNICODE character - typedef const WCHAR *LPCWSTR; - typedef const char *LPCSTR; - typedef WCHAR *LPWSTR; - typedef char *LPSTR; - - #ifdef _UNICODE - typedef wchar_t TCHAR; - typedef LPCWSTR LPCTSTR; - typedef LPWSTR LPTSTR; - #define _T(x) L ## x - #else /* _UNICODE */ // r_winnt - typedef char TCHAR; - typedef LPCSTR LPCTSTR; - typedef LPSTR LPTSTR; - #define _T(x) x - #endif /* _UNICODE */ // r_winnt - - +#ifdef ZIP_ARCHIVE_STL + #include "std_stl.h" #else - #include - #include - #ifndef STRICT - #define STRICT - #endif -#endif // #ifndef _WIN32 - -#ifndef ASSERT - #include - #define ASSERT(f) assert((f)) + #include "std_mfc.h" #endif -#ifndef VERIFY - #ifdef _DEBUG - #define VERIFY(x) ASSERT((x)) + +#ifdef TRACE + #if _MSC_VER >= 1300 + #define ZIPTRACE(f) TRACE(f,__FILE__,__LINE__) #else - #define VERIFY(x) x + #define ZIPTRACE(f) TRACE(_T(f)) + #endif +#else + #define ZIPTRACE(f) + #define NOZIPTRACE +#endif + + #ifdef _ZIP_STRICT_U16 + #define ZIP_INDEX_TYPE WORD + #define ZIP_VOLUME_TYPE WORD + #else + #define ZIP_INDEX_TYPE int + #define ZIP_VOLUME_TYPE int + #endif + + #define ZIP_SIZE_TYPE DWORD + #define ZIP_ZLIB_TYPE int + +#if !defined(_INTPTR_T_DEFINED) && !defined(__GNUC__) + /* NOTE: Harbour modification to make it compile with BCC55. [vszakats] */ + #if __BORLANDC__ > 0x551 + #include + #elif _MSC_VER <= 1200 || !defined _MSC_VER + typedef long intptr_t; #endif #endif +#define ZIP_FILE_INDEX_NOT_FOUND ZIP_INDEX_TYPE(-1) +#define ZIP_FILE_INDEX_UNSPECIFIED ZIP_FILE_INDEX_NOT_FOUND +#define ZIP_VOLUME_NUMBER_UNSPECIFIED ZIP_VOLUME_TYPE(-1) -#ifndef TRACE - #define TRACE(a,b,c) -#endif - -#if _MSC_VER >= 1300 - #define ZIP_ULONGLONG ULONGLONG - #define ZIP_LONGLONG LONGLONG -#else - #define ZIP_ULONGLONG DWORD - #define ZIP_LONGLONG LONG -#endif - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STDAFX_H__926F70F4_1B34_49AA_9532_498E8D2F3495__INCLUDED_) +#endif // !defined(ZIPARCHIVE_STDAFX_DOT_H) + diff --git a/harbour/contrib/hbziparch/zipabstractfile.h b/harbour/contrib/hbziparch/zipabstractfile.h deleted file mode 100644 index 8c9097b262..0000000000 --- a/harbour/contrib/hbziparch/zipabstractfile.h +++ /dev/null @@ -1,54 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipAbstractFile.h $ -// $Archive: /ZipArchive/ZipAbstractFile.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_ZIPABSTRACTFILE_H__46F247DE_21A6_4D12_AF64_B5A6B3CF4D57__INCLUDED_) -#define AFX_ZIPABSTRACTFILE_H__46F247DE_21A6_4D12_AF64_B5A6B3CF4D57__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -#include "ZipExport.h" -#include "zipstring.h" - -class ZIP_API CZipAbstractFile -{ -public: - - enum { begin = SEEK_SET, // 0 - current = SEEK_CUR, // 1 - end = SEEK_END // 2 - }; - CZipAbstractFile(){} - virtual bool Open(LPCTSTR , UINT , bool ){return true;} - virtual void Close() = 0; - virtual void Flush() = 0; - virtual ZIP_ULONGLONG GetPosition() const = 0; - virtual ZIP_ULONGLONG Seek(ZIP_LONGLONG lOff, int nFrom) = 0; - virtual ZIP_ULONGLONG GetLength() const = 0; - virtual void SetLength(ZIP_ULONGLONG nNewLen) = 0; - virtual ZIP_ULONGLONG SeekToBegin(){return Seek(0, begin);} - virtual ZIP_ULONGLONG SeekToEnd(){return Seek(0, end);} - virtual CZipString GetFilePath() const = 0; - virtual UINT Read(void *lpBuf, UINT nCount) = 0; - virtual void Write(const void* lpBuf, UINT nCount) = 0; - virtual bool IsClosed() const = 0; - virtual ~CZipAbstractFile(){}; - -}; - - - -#endif // !defined(AFX_ZIPABSTRACTFILE_H__46F247DE_21A6_4D12_AF64_B5A6B3CF4D57__INCLUDED_) diff --git a/harbour/contrib/hbziparch/ziparchive.cpp b/harbour/contrib/hbziparch/ziparchive.cpp deleted file mode 100644 index 2bea2ce30a..0000000000 --- a/harbour/contrib/hbziparch/ziparchive.cpp +++ /dev/null @@ -1,3235 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipArchive.cpp $ -// $Archive: /ZipArchive/ZipArchive.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" -#include "ziparchive.h" -// #include "ZipPathComponent.h" -#include "zipplatform.h" -#include "zipcompatibility.h" -#include - -#ifndef DEF_MEM_LEVEL -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -#endif - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -#define ZIP_COMPR_REPL_MASK 0xffffff00 -#define ZIP_COMPR_REPL_SIGN 0x0100 // first 8 bits should be 00 (reserved for compression level), next 8 should be different from ff (to distinguish from -1) - -const TCHAR CZipArchive::m_gszCopyright[] = {_T("ZipArchive library Copyright 2000 - 2003 Tadeusz Dracz")}; - - -void CZipAddNewFileInfo::Defaults() -{ - m_iSmartLevel = CZipArchive::zipsmSafeSmart; - m_iReplaceIndex = -1; - m_nBufSize = 65536; - m_iComprLevel = -1; // default - -} - -CZipArchive::CZipArchive() -{ - - m_bRemoveDriveLetter = true; - m_bIgnoreCRC = - m_bAutoFlush = false; - m_centralDir.m_pStorage= &m_storage; -// m_info.m_stream.zalloc = (alloc_func)_zliballoc; -// m_info.m_stream.zfree = (free_func)_zlibfree; -// m_bDetectZlibMemoryLeaks = true; - m_iFileOpened = nothing; - SetCaseSensitivity(ZipPlatform::GetSystemCaseSensitivity()); -} - - -CZipArchive::~CZipArchive() -{ - // Close(); // cannot be here: if an exception is thrown strange things can happen - EmptyPtrList(); - -} - - - -void CZipArchive::Open(LPCTSTR szPathName, int iMode, int iVolumeSize) -{ - if (!IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive already opened.\n"),__FILE__,__LINE__); - return; - } - m_storage.Open(szPathName, iMode, iVolumeSize); - OpenInternal(iMode); -} - -void CZipArchive::Open(CZipMemFile& mf,int iMode) -{ - if (!IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive already opened.\n"),__FILE__,__LINE__); - return; - } - if (iMode != zipOpen && iMode != zipOpenReadOnly && iMode != zipCreate) - { - TRACE(_T("%s(%i) : Mode not supported.\n"),__FILE__,__LINE__); - return; - } - m_storage.Open(mf, iMode); - OpenInternal(iMode); -} - - -void CZipArchive::OpenInternal(int iMode) -{ - m_pszPassword.Release(); - m_iFileOpened = nothing; - m_centralDir.Init(); - m_iArchiveSystCompatib = ZipPlatform::GetSystemID(); - m_szRootPath.Empty(); - if ((iMode == zipOpen) ||(iMode == zipOpenReadOnly)) - { - m_centralDir.Read(); - // if there is at least one file, get system comp. from the first one - if (m_centralDir.IsValidIndex(0)) - { - int iSystemComp = m_centralDir[0]->GetSystemCompatibility(); - if (ZipCompatibility::IsPlatformSupported(iSystemComp)) - m_iArchiveSystCompatib = iSystemComp; - } - } - -} - - -bool CZipArchive::IsClosed(bool bArchive) const -{ - return bArchive ?(m_storage.GetCurrentDisk() == -1):(!m_storage.m_pFile || m_storage.m_pFile->IsClosed()); -} - - -void CZipArchive::ThrowError(int err, bool bZlib) -{ - if (bZlib) - err = CZipException::ZlibErrToZip(err); - CZipException::Throw(err, IsClosed() ? _T("") : (LPCTSTR)m_storage.m_pFile->GetFilePath()); -} - - - -bool CZipArchive::GetFileInfo(CZipFileHeader & fhInfo, WORD uIndex) const -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - - if (!m_centralDir.IsValidIndex(uIndex)) - return false; - - fhInfo = *(m_centralDir[uIndex]); - m_centralDir.ConvertFileName(true, false, &fhInfo); - return true; -} - -int CZipArchive::FindFile(LPCTSTR lpszFileName, int iCaseSensitive, bool bFileNameOnly) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return (int)-1; - } - bool bCS; - bool bSporadically; - switch (iCaseSensitive) - { - case ffCaseSens: - bCS = true; - bSporadically = true; - break; - case ffNoCaseSens: - bCS = false; - bSporadically = true; - break; - default: - bCS = m_bCaseSensitive; - bSporadically = false; - } - return m_centralDir.FindFile(lpszFileName, bCS, bSporadically, bFileNameOnly); -} - -bool CZipArchive::OpenFile(WORD uIndex) -{ - if (!m_centralDir.IsValidIndex(uIndex)) - { - ASSERT(FALSE); - return false; - } - if (m_storage.IsSpanMode() == 1) - { - TRACE(_T("%s(%i) : You cannot extract from the span in creation.\n"),__FILE__,__LINE__); - return false; - } - - - if (m_iFileOpened) - { - TRACE(_T("%s(%i) : A file already opened.\n"),__FILE__,__LINE__); - return false; - } - - m_info.Init(); - m_centralDir.OpenFile(uIndex); - if (CurrentFile()->IsEncrypted()) - { - - if (m_pszPassword.GetSize() == 0) - { - TRACE(_T("%s(%i) : Password not set for the encrypted file.\n"),__FILE__,__LINE__); - ThrowError(CZipException::badPassword); - } - CryptInitKeys(); - if (!CryptCheck()) - ThrowError(CZipException::badPassword); - - } - else if (m_pszPassword.GetSize() != 0) - { - TRACE(_T("%s(%i) : Password set for a not encrypted file. Ignoring password.\n"),__FILE__,__LINE__); - } - - WORD uMethod = CurrentFile()->m_uMethod; - - if ((uMethod != 0) &&(uMethod != Z_DEFLATED)) - ThrowError(CZipException::badZipFile); - - if (uMethod == Z_DEFLATED) - { -// m_info.m_stream.opaque = m_bDetectZlibMemoryLeaks ? &m_list : 0; - int err = inflateInit2(&m_info.m_stream, -MAX_WBITS); - // * windowBits is passed < 0 to tell that there is no zlib header. - // * Note that in this case inflate *requires* an extra "dummy" byte - // * after the compressed stream in order to complete decompression and - // * return Z_STREAM_END. - CheckForError(err); - } - m_info.m_uComprLeft = CurrentFile()->m_uComprSize; - if (CurrentFile()->IsEncrypted()) - m_info.m_uComprLeft -= ZIPARCHIVE_ENCR_HEADER_LEN; - m_info.m_uUncomprLeft = CurrentFile()->m_uUncomprSize; - m_info.m_uCrc32 = 0; - m_info.m_stream.total_out = 0; - m_info.m_stream.avail_in = 0; - - m_iFileOpened = extract; - return true; -} - - -int CZipArchive::GetLocalExtraField(char *pBuf, int iSize)const -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return -1; - } - - if (m_iFileOpened != extract) - { - TRACE(_T("%s(%i) : A file must be opened to get the local extra field.\n"),__FILE__,__LINE__); - return -1; - } - - int size = m_centralDir.m_pLocalExtraField.GetSize(); - if (!pBuf|| !size) - return size; - - if (iSize < size) - size = iSize; - - memcpy(pBuf, m_centralDir.m_pLocalExtraField, size); - return size; -} - -/* -void* CZipArchive::_zliballoc(void* opaque, UINT items, UINT size) -{ - void* p = new char[size * items]; - if (opaque) - { - CZipPtrList* list = (CZipPtrList*) opaque; - list->AddTail(p); - } - return p; -} - -void CZipArchive::_zlibfree(void* opaque, void* address) -{ - if (opaque) - { - CZipPtrList* list = (CZipPtrList*) opaque; - CZipPtrListIter iter = list->Find(address); - if (list->IteratorValid(iter)) - list->RemoveAt(iter); - } - delete[] (char*) address; -} -*/ - -void CZipArchive::CheckForError(int iErr) -{ - if ((iErr == Z_OK) ||(iErr == Z_NEED_DICT)) - return; - - ThrowError(iErr, true); -} - -CZipFileHeader* CZipArchive::CurrentFile() -{ - ASSERT(m_centralDir.m_pOpenedFile); - return m_centralDir.m_pOpenedFile; -} - -DWORD CZipArchive::ReadFile(void *pBuf, - DWORD iSize) -{ - if (m_iFileOpened != extract) - { - TRACE(_T("%s(%i) : Current file must be opened.\n"),__FILE__,__LINE__); - return 0; - } - - if (!pBuf || !iSize) - return 0; - - m_info.m_stream.next_out = (Bytef*)pBuf; - m_info.m_stream.avail_out = iSize > m_info.m_uUncomprLeft - ? m_info.m_uUncomprLeft : iSize; - - - DWORD iRead = 0; - - // may happen when the file is 0 sized - bool bForce = m_info.m_stream.avail_out == 0 && m_info.m_uComprLeft > 0; - while (m_info.m_stream.avail_out > 0 || (bForce && m_info.m_uComprLeft > 0)) - { - if ((m_info.m_stream.avail_in == 0) && - (m_info.m_uComprLeft >= 0)) // Also when there are zero bytes left! - { - DWORD uToRead = m_info.m_pBuffer.GetSize(); - if (m_info.m_uComprLeft < uToRead) - uToRead = m_info.m_uComprLeft; - - if (uToRead == 0) - { - uToRead = 1; // Add dummy byte at end of compressed data. - } - else - { - m_storage.Read(m_info.m_pBuffer, uToRead, false); - CryptDecodeBuffer(uToRead); - } - - m_info.m_uComprLeft -= uToRead; - - m_info.m_stream.next_in = (Bytef*)(char*)m_info.m_pBuffer; - m_info.m_stream.avail_in = uToRead; - } - - if (CurrentFile()->m_uMethod == 0) - { - DWORD uToCopy = m_info.m_stream.avail_out < m_info.m_stream.avail_in - ? m_info.m_stream.avail_out : m_info.m_stream.avail_in; - - memcpy(m_info.m_stream.next_out, m_info.m_stream.next_in, uToCopy); - - m_info.m_uCrc32 = crc32(m_info.m_uCrc32, m_info.m_stream.next_out, uToCopy); - - m_info.m_uUncomprLeft -= uToCopy; - m_info.m_stream.avail_in -= uToCopy; - m_info.m_stream.avail_out -= uToCopy; - m_info.m_stream.next_out += uToCopy; - m_info.m_stream.next_in += uToCopy; - m_info.m_stream.total_out += uToCopy; - iRead += uToCopy; - } - else - { - DWORD uTotal = m_info.m_stream.total_out; - Bytef* pOldBuf = m_info.m_stream.next_out; - int err = inflate(&m_info.m_stream, Z_SYNC_FLUSH); - DWORD uToCopy = m_info.m_stream.total_out - uTotal; - - m_info.m_uCrc32 = crc32(m_info.m_uCrc32, pOldBuf, uToCopy); - - m_info.m_uUncomprLeft -= uToCopy; - iRead += uToCopy; - - if (err == Z_STREAM_END) - return iRead; - - CheckForError(err); - } - } - - return iRead; -} - -void CZipArchive::Close(int iAfterException, bool bUpdateTimeStamp) -{ - // if after an exception - the archive may be closed, but the file may be opened - if (IsClosed() && (!iAfterException || IsClosed(false))) - { - TRACE(_T("%s(%i) : ZipArchive is already closed.\n"),__FILE__,__LINE__); - return; - } - - if (m_iFileOpened == extract) - CloseFile(NULL, iAfterException != afNoException); - - if (m_iFileOpened == compress) - CloseNewFile(iAfterException != afNoException); - - if (iAfterException != afAfterException && !IsClosed(false)) // in disk spanning when user aborts - WriteCentralDirectory(false); // we will flush in CZipStorage::Close - - time_t tNewestTime = 0; - - if (bUpdateTimeStamp) - { - int iSize = m_centralDir.m_headers.GetSize(); - for (int i = 0; i< iSize; i++) - { - time_t tFileInZipTime = m_centralDir[i]->GetTime(); - if (tFileInZipTime > tNewestTime) - tNewestTime = tFileInZipTime; - } - } - m_centralDir.Clear(); - CZipString szFileName = m_storage.Close(iAfterException == afAfterException); - if (bUpdateTimeStamp && !szFileName.IsEmpty()) - ZipPlatform::SetFileModTime(szFileName, tNewestTime); -} - -void CZipArchive::WriteCentralDirectory(bool bFlush) -{ - m_centralDir.Write(GetCallback(cbSave)); - if (bFlush) - m_storage.Flush(); -} - -void CZipArchive::SetCallback(CZipActionCallback* pCallback, int iWhich) -{ - CallbackType cbs[] = {cbAdd, cbAddTmp, cbAddStore,cbExtract,cbDeleteCnt,cbDelete,cbTest,cbSave, cbGetFromArchive, cbRename, cbReplace}; - int iCount = sizeof(cbs)/sizeof(CallbackType); - for (int i = 0; i < iCount; i++) - { - CallbackType iCallback = cbs[i]; - if (iWhich & iCallback) - m_callbacks.Set(pCallback, iCallback); - } -} - -void CZipArchive::SetAdvanced(int iWriteBuffer, int iGeneralBuffer, int iSearchBuffer) -{ - if (!IsClosed()) - { - TRACE(_T("%s(%i) : Set this options before opening the archive.\n"),__FILE__,__LINE__); - return; - } - - m_storage.m_iWriteBufferSize = iWriteBuffer < 1024 ? 1024 : iWriteBuffer; - m_info.m_iBufferSize = iGeneralBuffer < 1024 ? 1024 : iGeneralBuffer; - m_centralDir.m_iBufferSize = iSearchBuffer < 1024 ? 1024 : iSearchBuffer; -} - -int CZipArchive::CloseFile(CZipFile &file) -{ - CZipString temp = file.GetFilePath(); - file.Close(); - return CloseFile(temp); -} - -int CZipArchive::CloseFile(LPCTSTR lpszFilePath, bool bAfterException) -{ - if (m_iFileOpened != extract) - { - TRACE(_T("%s(%i) : No opened file.\n"),__FILE__,__LINE__); - return false; - } - - int iRet = 1; - if (!bAfterException) - { - if (m_info.m_uUncomprLeft == 0) - { - if (!m_bIgnoreCRC && m_info.m_uCrc32 != CurrentFile()->m_uCrc32) - ThrowError(CZipException::badCrc); - } - else - iRet = -1; - - - if (CurrentFile()->m_uMethod == Z_DEFLATED) - inflateEnd(&m_info.m_stream); - - - if (lpszFilePath) - { - - if (!ZipPlatform::SetFileModTime(lpszFilePath, CurrentFile()->GetTime()) - ||!ZipPlatform::SetFileAttr(lpszFilePath, CurrentFile()->GetSystemAttr())) - iRet = -2; - } - - } - - m_centralDir.CloseFile(bAfterException); - - m_iFileOpened = nothing; - m_info.ReleaseBuf(); - EmptyPtrList(); - return iRet; -} - -bool CZipArchive::OpenNewFile(CZipFileHeader & header, - int iLevel, - LPCTSTR lpszFilePath, DWORD uInternal) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - - if (m_iFileOpened) - { - TRACE(_T("%s(%i) : A file already opened.\n"),__FILE__,__LINE__); - return false; - } - - if (m_storage.IsSpanMode() == -1) - { - TRACE(_T("%s(%i) : You cannot add files to the existing disk spannig archive.\n"),__FILE__,__LINE__); - return false; - } - - if (GetCount() ==(WORD)USHRT_MAX) - { - TRACE(_T("%s(%i) : Maximum file count inside archive reached.\n"),__FILE__,__LINE__); - return false; - } - - DWORD uAttr = 0; // ..compiler - time_t ttime; - if (lpszFilePath) - { - - if (!ZipPlatform::GetFileAttr(lpszFilePath, uAttr)) - // do not continue - if the file was a directory then not recognizing it will cause - // serious errors (need uAttr to recognize it) - return false; - if (!ZipPlatform::GetFileModTime(lpszFilePath, ttime)) - ttime = time(NULL); - } - - m_info.Init(); - - - if (lpszFilePath) - { - header.SetTime(ttime); - SetFileHeaderAttr(header, uAttr); // set system compatibility as well - } - else - header.SetSystemCompatibility(m_iArchiveSystCompatib); - - CZipString szFileName = header.GetFileName(); - - - bool bIsDirectory = header.IsDirectory(); - if (bIsDirectory) - { - int iNameLen = szFileName.GetLength(); - if (!iNameLen || !CZipPathComponent::IsSeparator(szFileName[iNameLen-1])) - { - szFileName += CZipPathComponent::m_cSeparator; - header.SetFileName(szFileName); - } - } - - if (szFileName.IsEmpty()) - { - szFileName.Format(_T("file%i"), GetCount()); - header.SetFileName(szFileName); - } - - // make sure that all slashes are correct (as the current system default) - // because AddNewFile calls InsertFindFastElement if necessary and - // the find array keeps all the files already converted to the current system standards - // we do not perform Oem->Ansi here, because who would pass oem values here? - // - ZipCompatibility::SlashBackslashChg(header.m_pszFileName, true); - - bool bEncrypted = m_pszPassword.GetSize() != 0; - -#ifdef _DEBUG - if (bIsDirectory && bEncrypted) - TRACE(_T("%s(%i) : Encrypting a directory. It's pointless.\n\ - Clear the password before adding a directory.\n"),__FILE__,__LINE__); -#endif - - - - int iReplaceIndex = -1; - bool bReplace = (iLevel & 0xffff) == ZIP_COMPR_REPL_SIGN; - if (bReplace) - { - int iMask = ZIP_COMPR_REPL_MASK; - iReplaceIndex = (iLevel & iMask) >> 16; - iLevel = (char)(iLevel & ~iMask); - ASSERT(iLevel == 0); - } - else - uInternal = 0; - - if (iLevel < -1 || iLevel > 9) - iLevel = -1; - - if (!header.PrepareData(iLevel, m_storage.IsSpanMode() == 1, bEncrypted)) - ThrowError(CZipException::tooLongFileName); - - if (bReplace) - { - uInternal += header.GetSize(true); - if (header.IsEncrypted()) - uInternal += ZIPARCHIVE_ENCR_HEADER_LEN; - if (header.IsDataDescr()) - uInternal += ZIPARCHIVE_DATADESCRIPTOR_LEN + 4; // CZipCentralDir::CloseNewFile - } - m_centralDir.AddNewFile(header, iReplaceIndex); - if (bReplace) - MakeSpaceForReplace(iReplaceIndex, uInternal, szFileName); - - // this ensures the conversion will take place anyway (must take because we are going - // to write the local header in a moment - m_centralDir.ConvertFileName(false, m_centralDir.m_bConvertAfterOpen); - - CurrentFile()->WriteLocal(m_storage); - - // we have written the local header, but if we keep filenames not converted - // in memory , we have to restore the non-converted value - if (m_centralDir.m_bConvertAfterOpen) - CurrentFile()->SetFileName(szFileName); - - if (bEncrypted) - { - CZipAutoBuffer buf(ZIPARCHIVE_ENCR_HEADER_LEN); - // use pseudo-crc since we don't know it yet - CryptCryptHeader((long)header.m_uModTime << 16, buf); - m_storage.Write(buf, ZIPARCHIVE_ENCR_HEADER_LEN, false); - } - - - m_info.m_uComprLeft = 0; - m_info.m_stream.avail_in = (uInt)0; - m_info.m_stream.avail_out = (uInt)m_info.m_pBuffer.GetSize(); - m_info.m_stream.next_out = (Bytef*)(char*)m_info.m_pBuffer; - m_info.m_stream.total_in = 0; - m_info.m_stream.total_out = 0; - - if (bIsDirectory && (CurrentFile()->m_uMethod != 0)) - CurrentFile()->m_uMethod = 0; - - if (CurrentFile()->m_uMethod == Z_DEFLATED) - { -// m_info.m_stream.opaque = m_bDetectZlibMemoryLeaks ? &m_list : 0; - - int err = deflateInit2(&m_info.m_stream, iLevel, - Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); - - CheckForError(err); - } - m_iFileOpened = compress; - return true; -} - - -bool CZipArchive::ExtractFile(WORD uIndex, - LPCTSTR lpszPath, - bool bFullPath, - LPCTSTR lpszNewName, - DWORD nBufSize) -{ - - if (!nBufSize && !lpszPath) - return false; - - CZipFileHeader header; - GetFileInfo(header, uIndex); // to ensure that slash and oem conversions take place - CZipString szFileNameInZip = (LPCTSTR)header.GetFileName(); - CZipString szFile = PredictExtractedFileName(szFileNameInZip, lpszPath, bFullPath, lpszNewName); - CZipActionCallback* pCallback = GetCallback(cbExtract); - if (pCallback) - pCallback->Init(szFileNameInZip, szFile); - - - if (header.IsDirectory()) - { - if (pCallback) - pCallback->SetTotal(0); // in case of calling LeftToDo afterwards - - ZipPlatform::ForceDirectory(szFile); - ZipPlatform::SetFileAttr(szFile, header.GetSystemAttr()); - - if (pCallback) - pCallback->CallbackEnd(); - return true; - } - else - { - if (pCallback) - pCallback->SetTotal(header.m_uUncomprSize); - - if (!OpenFile(uIndex)) - return false; - - CZipPathComponent zpc(szFile); - ZipPlatform::ForceDirectory(zpc.GetFilePath()); - CZipFile f(szFile, CZipFile::modeWrite | - CZipFile::modeCreate | CZipFile::shareDenyWrite); - DWORD iRead; - CZipAutoBuffer buf(nBufSize); - int iAborted = 0; - do - { - iRead = ReadFile(buf, buf.GetSize()); - if (iRead) - { - f.Write(buf, iRead); - if (pCallback) - if (!(*pCallback)(iRead)) - { - if (iRead == buf.GetSize() && ReadFile(buf, 1) != 0) // test one byte if there is something left - iAborted = CZipException::abortedAction; - else - iAborted = CZipException::abortedSafely; // we did it! - break; - } - - } - } - while (iRead == buf.GetSize()); - bool bRet = CloseFile(f) == 1; - if (!bRet && iAborted == CZipException::abortedSafely) - iAborted = CZipException::abortedAction; // sorry, finished, but not successfull - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - CZipException::Throw(iAborted, szFile); // throw to distuingiush from other return codes - return bRet; - - } -} - -bool CZipArchive::ExtractFile(WORD uIndex, - CZipMemFile& mf, - DWORD nBufSize) -{ - if (!nBufSize) - return false; - - CZipFileHeader header; - GetFileInfo(header, uIndex); // to ensure that slash and oem conversions take place - CZipActionCallback* pCallback = GetCallback(cbExtract); - if (pCallback) - { - pCallback->Init(header.GetFileName()); - pCallback->SetTotal(header.m_uUncomprSize); - } - - if (header.IsDirectory() || !OpenFile(uIndex)) - return false; - - - - - CZipAutoBuffer buf(nBufSize); - mf.SeekToEnd(); - DWORD iRead; - int iAborted = 0; - do - { - iRead = ReadFile(buf, buf.GetSize()); - if (iRead) - { - mf.Write(buf, iRead); - if (pCallback) - if (!(*pCallback)(iRead)) - { - if (iRead == buf.GetSize() && ReadFile(buf, 1) != 0) // test one byte if there is something left - iAborted = CZipException::abortedAction; - else - iAborted = CZipException::abortedSafely; // we did it! - break; - } - } - } - while (iRead == buf.GetSize()); - bool bRet = CloseFile() == 1; - if (!bRet && iAborted == CZipException::abortedSafely) - iAborted = CZipException::abortedAction; // sorry, finished, but not successfull - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - CZipException::Throw(iAborted); // throw to distuingiush from other return codes - return bRet; -} - - -void CZipArchive::SetExtraField(const char *pBuf, WORD iSize) -{ - if (m_iFileOpened != compress) - { - TRACE(_T("%s(%i) : A new file must be opened.\n"),__FILE__,__LINE__); - return; - } - if (!pBuf || !iSize) - return; - - CurrentFile()->m_pExtraField.Allocate(iSize); - memcpy(CurrentFile()->m_pExtraField, pBuf, iSize); -} - -bool CZipArchive::WriteNewFile(const void *pBuf, DWORD iSize) -{ - if (m_iFileOpened != compress) - { - TRACE(_T("%s(%i) : A new file must be opened.\n"),__FILE__,__LINE__); - return false; - } - - - m_info.m_stream.next_in = (Bytef*)pBuf; - m_info.m_stream.avail_in = iSize; - CurrentFile()->m_uCrc32 = crc32(CurrentFile()->m_uCrc32, (Bytef*)pBuf, iSize); - - - while (m_info.m_stream.avail_in > 0) - { - if (m_info.m_stream.avail_out == 0) - { - CryptEncodeBuffer(); - m_storage.Write(m_info.m_pBuffer, m_info.m_uComprLeft, false); - m_info.m_uComprLeft = 0; - m_info.m_stream.avail_out = m_info.m_pBuffer.GetSize(); - m_info.m_stream.next_out = (Bytef*)(char*)m_info.m_pBuffer; - } - - if (CurrentFile()->m_uMethod == Z_DEFLATED) - { - DWORD uTotal = m_info.m_stream.total_out; - int err = deflate(&m_info.m_stream, Z_NO_FLUSH); - CheckForError(err); - m_info.m_uComprLeft += m_info.m_stream.total_out - uTotal; - } - else - { - DWORD uToCopy = (m_info.m_stream.avail_in < m_info.m_stream.avail_out) - ? m_info.m_stream.avail_in : m_info.m_stream.avail_out; - - memcpy(m_info.m_stream.next_out, m_info.m_stream.next_in, uToCopy); - - m_info.m_stream.avail_in -= uToCopy; - m_info.m_stream.avail_out -= uToCopy; - m_info.m_stream.next_in += uToCopy; - m_info.m_stream.next_out += uToCopy; - m_info.m_stream.total_in += uToCopy; - m_info.m_stream.total_out += uToCopy; - m_info.m_uComprLeft += uToCopy; - } - } - - return true; -} - -bool CZipArchive::CloseNewFile(bool bAfterException) -{ - if (m_iFileOpened != compress) - { - TRACE(_T("%s(%i) : A new file must be opened.\n"),__FILE__,__LINE__); - return false; - } - - m_info.m_stream.avail_in = 0; - if (!bAfterException) - { - int err = Z_OK; - if (CurrentFile()->m_uMethod == Z_DEFLATED) - while (err == Z_OK) - { - if (m_info.m_stream.avail_out == 0) - { - CryptEncodeBuffer(); - m_storage.Write(m_info.m_pBuffer, m_info.m_uComprLeft, false); - m_info.m_uComprLeft = 0; - m_info.m_stream.avail_out = m_info.m_pBuffer.GetSize(); - m_info.m_stream.next_out = (Bytef*)(char*)m_info.m_pBuffer; - } - DWORD uTotal = m_info.m_stream.total_out; - err = deflate(&m_info.m_stream, Z_FINISH); - m_info.m_uComprLeft += m_info.m_stream.total_out - uTotal; - } - - if (err == Z_STREAM_END) - err = Z_OK; - CheckForError(err); - - if (m_info.m_uComprLeft > 0) - { - CryptEncodeBuffer(); - m_storage.Write(m_info.m_pBuffer, m_info.m_uComprLeft, false); - } - - if (CurrentFile()->m_uMethod == Z_DEFLATED) - { - err = deflateEnd(&m_info.m_stream); - CheckForError(err); - } - - - // it may be increased by the encrypted header size - CurrentFile()->m_uComprSize += m_info.m_stream.total_out; - CurrentFile()->m_uUncomprSize = m_info.m_stream.total_in; - - m_centralDir.CloseNewFile(); - } - else - m_centralDir.m_pOpenedFile = NULL; - - m_iFileOpened = nothing; - m_info.ReleaseBuf(); - EmptyPtrList(); - - if (m_bAutoFlush && !bAfterException) - Flush(); - - return true; -} - -void CZipArchive::DeleteFile(WORD uIndex) -{ - CZipWordArray indexes; - indexes.Add(uIndex); - DeleteFiles(indexes); -} - -void CZipArchive::GetIndexes(const CZipStringArray &aNames, CZipWordArray& aIndexes) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return; - } - int iSize = aNames.GetSize(); - for (WORD i = 0; i < iSize; i++) - { - int idx = FindFile(aNames[i], ffDefault, false); - if (idx != -1) - aIndexes.Add((WORD)idx); - } -} - -void CZipArchive::DeleteFiles(const CZipStringArray &aNames) -{ - CZipWordArray indexes; - GetIndexes(aNames, indexes); - DeleteFiles(indexes); -} - - -void CZipArchive::DeleteFiles(CZipWordArray &aIndexes) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return; - } - - if (m_storage.IsSpanMode()) - { - TRACE(_T("%s(%i) : You cannot delete files from the disk spannig archive.\n"),__FILE__,__LINE__); - return; - } - - if (m_iFileOpened) - { - TRACE(_T("%s(%i) : You cannot delete files if there is a file opened.\n"),__FILE__,__LINE__); - return; - } - - CZipActionCallback* pCallback = GetCallback(cbDeleteCnt); - if (pCallback) - pCallback->Init(); - - int uSize = aIndexes.GetSize(); - if (!uSize) - { - TRACE(_T("%s(%i) : The indekses array is empty.\n"),__FILE__,__LINE__); - return; - } - - // remove all - that's easy so don't waste the time - if (uSize == GetCount()) - { - pCallback = GetCallback(cbDelete); - if (pCallback) - { - // do it right and sent the notification - pCallback->Init(); - pCallback->SetTotal(uSize); - } - - m_centralDir.RemoveFromDisk(); - m_storage.m_pFile->SetLength(m_centralDir.GetBytesBefore()); - m_centralDir.RemoveAll(); - if (m_bAutoFlush) - Flush(); - if (pCallback) - pCallback->CallbackEnd(); - return; - } - - aIndexes.Sort(true); - - CZipArray aInfo; - - int iDelIndex = 0; - - - int iStep = 0; // for the compiler - if (pCallback) - { - pCallback->SetTotal(GetCount()); - iStep = CZipActionCallback::m_iStep; // we don't want to wait forever - } - - int i; - int uMaxDelIndex = aIndexes[uSize - 1]; - for (i = aIndexes[0]; i < GetCount(); i++) - { - CZipFileHeader* pHeader = m_centralDir[i]; - bool bDelete; - if (i <= uMaxDelIndex && i == aIndexes[iDelIndex]) - { - iDelIndex++; - bDelete = true; - } - else - bDelete = false; - aInfo.Add(CZipDeleteInfo(pHeader, bDelete)); - if (pCallback && (!(i % iStep))) - if (!(*pCallback)(iStep)) - ThrowError(CZipException::abortedSafely); - } - ASSERT(iDelIndex == uSize); - - uSize = aInfo.GetSize(); - if (!uSize) // it is possible - return; - - // now we start deleting (not safe to break) - pCallback = GetCallback(cbDelete); - if (pCallback) - pCallback->Init(); - - - m_centralDir.RemoveFromDisk(); - - DWORD uTotalToMoveBytes = 0, uLastOffset = m_storage.m_pFile->GetLength() - m_centralDir.GetBytesBefore(); - // count the number of bytes to move - for (i = uSize - 1; i >=0 ; i--) - { - const CZipDeleteInfo& di = aInfo[i]; - if (!di.m_bDelete) - uTotalToMoveBytes += uLastOffset - di.m_pHeader->m_uOffset; - uLastOffset = di.m_pHeader->m_uOffset; - } - if (pCallback) - pCallback->CallbackEnd(); - - - if (pCallback) - pCallback->SetTotal(uTotalToMoveBytes); - - - m_info.Init(); - - DWORD uMoveBy = 0, uOffsetStart = 0; - for (i = 0; i < uSize; i++) - { - const CZipDeleteInfo& di = aInfo[i]; - - if (di.m_bDelete) - { - // next hole - DWORD uTemp = di.m_pHeader->m_uOffset; - m_centralDir.RemoveFile(di.m_pHeader); // first remove - if (uOffsetStart) - { - // copy the files over a previous holes - MovePackedFiles(uOffsetStart, uTemp, uMoveBy, pCallback); - uOffsetStart = 0; // never be at the beginning, because the first file is always to be deleted - } - if (i == uSize - 1) - uTemp = (m_storage.m_pFile->GetLength() - m_centralDir.GetBytesBefore()) - uTemp; - else - uTemp = aInfo[i+1].m_pHeader->m_uOffset - uTemp; - - uMoveBy += uTemp; - - } - else - { - if (uOffsetStart == 0) // find contiuos area to move - uOffsetStart = di.m_pHeader->m_uOffset; - di.m_pHeader->m_uOffset -= uMoveBy; - } - - } - if (uOffsetStart) - MovePackedFiles(uOffsetStart, - m_storage.m_pFile->GetLength() - m_centralDir.GetBytesBefore(), - uMoveBy, pCallback); - - m_info.ReleaseBuf(); - if (uMoveBy) // just in case - m_storage.m_pFile->SetLength(m_storage.m_pFile->GetLength() - uMoveBy); - - if (pCallback) - pCallback->CallbackEnd(); - - if (m_bAutoFlush) - Flush(); -} - - - -bool CZipArchive::AddNewFile(LPCTSTR lpszFilePath, - int iComprLevel, - bool bFullPath, - int iSmartLevel, - unsigned long nBufSize) -{ - - CZipAddNewFileInfo zanfi (lpszFilePath, bFullPath); - zanfi.m_iComprLevel = iComprLevel; - zanfi.m_iSmartLevel = zipsmSafeSmart; - zanfi.m_nBufSize = nBufSize; - return AddNewFile(zanfi); -} - -bool CZipArchive::AddNewFileDrv(LPCTSTR lpszFilePath, - int iComprLevel, - bool bFullPath, - int iSmartLevel, - unsigned long nBufSize) -{ - - CZipAddNewFileInfo zanfi (lpszFilePath, bFullPath); - zanfi.m_iComprLevel = iComprLevel; - zanfi.m_iSmartLevel = zipsmSafeSmart; - zanfi.m_nBufSize = nBufSize; - return AddNewFileDrv(zanfi); -} - -bool CZipArchive::AddNewFile(LPCTSTR lpszFilePath, - LPCTSTR lpszFileNameInZip, - int iComprLevel, - int iSmartLevel, - unsigned long nBufSize) -{ - CZipAddNewFileInfo zanfi(lpszFilePath, lpszFileNameInZip); - zanfi.m_iComprLevel = iComprLevel; - zanfi.m_iSmartLevel = zipsmSafeSmart; - zanfi.m_nBufSize = nBufSize; - return AddNewFile(zanfi); -} - -bool CZipArchive::AddNewFile(CZipMemFile& mf, - LPCTSTR lpszFileNameInZip, - int iComprLevel, - int iSmartLevel, - unsigned long nBufSize) -{ - CZipAddNewFileInfo zanfi(&mf, lpszFileNameInZip); - zanfi.m_iComprLevel = iComprLevel; - zanfi.m_iSmartLevel = zipsmSafeSmart; - zanfi.m_nBufSize = nBufSize; - return AddNewFile(zanfi); -} - - -bool CZipArchive::AddNewFileDrv(CZipAddNewFileInfo& info) -{ - // no need for ASSERT and TRACE here - it will be done by OpenNewFile - - if (!m_info.m_iBufferSize) - return false; - CZipPathComponent::RemoveSeparators(info.m_szFilePath); - if (!info.m_szFilePath.IsEmpty()) // it may be empty after removing sep. - { - if (info.m_szFileNameInZip.IsEmpty()) - { - CZipPathComponent zpc(info.m_szFilePath); - info.m_szFileNameInZip = info.m_bFullPath ? zpc.GetNoDrive() : TrimRootPath(zpc); - } - } - else if (!info.m_pFile) - return false; - - bool bSpan = GetSpanMode() != 0; - - // checking the iReplace index - if (!UpdateReplaceIndex(info.m_iReplaceIndex, info.m_szFileNameInZip)) - return false; - - bool bReplace = info.m_iReplaceIndex >= 0; - - DWORD uAttr; - time_t ttime; - if (info.m_pFile) - { - uAttr = ZipPlatform::GetDefaultAttributes(); - ttime = time(NULL); - } - else - { - if (!ZipPlatform::GetFileAttr(info.m_szFilePath, uAttr)) - return false; // we don't know whether it is a file or a directory - if (!ZipPlatform::GetFileModTime(info.m_szFilePath, ttime)) - ttime = time(NULL); - } - CZipFileHeader header; - header.SetFileName(info.m_szFileNameInZip); - if (ZipPlatform::GetSystemID() != ZipCompatibility::zcUnix) - uAttr |= ZipCompatibility::ConvertToSystem(uAttr, ZipPlatform::GetSystemID(), ZipCompatibility::zcUnix); // make it readable under Unix as well, since it stores its attributes in HIWORD(uAttr) - SetFileHeaderAttr(header, uAttr); - header.SetTime(ttime); - bool bInternal = (info.m_iSmartLevel & zipsmInternal01) != 0; - CZipActionCallback* pCallback = NULL; - if (!bInternal) - { - pCallback = GetCallback(cbAdd); - if (pCallback) - pCallback->Init(info.m_szFileNameInZip, info.m_szFilePath); - } - - - - if (header.IsDirectory()) // will never be when m_pFile is not NULL, so we don't check it - { - ASSERT(!info.m_pFile); // should never happened - ASSERT(!bInternal); - - if (pCallback) - pCallback->SetTotal(0); // in case of calling LeftToDo afterwards - - // clear password for a directory - bool bRet = false; - CZipSmClrPass smcp; - if (info.m_iSmartLevel & zipsmCPassDir) - smcp.ClearPasswordSmartly(this); - - bRet = OpenNewFile(header, bReplace ? (info.m_iReplaceIndex << 16) | ZIP_COMPR_REPL_SIGN : 0); - - CloseNewFile(); - if (pCallback) - pCallback->CallbackEnd(); - - return bRet; - } - - CZipSmClrPass smcp; - bool bIsCompression = info.m_iComprLevel != 0; - bool bEff = (info.m_iSmartLevel & zipsmCheckForEff)&& bIsCompression; - bool bCheckForZeroSized = (info.m_iSmartLevel & zipsmCPFile0) && !GetPassword().IsEmpty(); - bool bCheckForSmallFiles = (info.m_iSmartLevel & zipsmNotCompSmall) && bIsCompression; - DWORD iFileSize = DWORD(-1); - bool bNeedTempArchive = (bEff && bSpan) || (bReplace && bIsCompression); - if (bCheckForSmallFiles || bCheckForZeroSized || bNeedTempArchive) - { - - if (info.m_pFile) - iFileSize = info.m_pFile->GetLength(); - else - { - if (!ZipPlatform::GetFileSize(info.m_szFilePath, iFileSize) && bEff) - bEff = false; // the file size is needed only when eff. in span mode - } - if (iFileSize != DWORD(-1)) - { - if (bCheckForZeroSized && iFileSize == 0) - smcp.ClearPasswordSmartly(this); - if (bCheckForSmallFiles && iFileSize < 5) - info.m_iComprLevel = 0; - } - } - bool bEffInMem = bEff && (info.m_iSmartLevel & zipsmMemoryFlag); - CZipString szTempFileName; - if (bNeedTempArchive && (bEffInMem || - !(szTempFileName = ZipPlatform::GetTmpFileName( - m_szTempPath.IsEmpty() ? NULL : (LPCTSTR)m_szTempPath, iFileSize) - ).IsEmpty())) - { - CZipMemFile* pmf = NULL; - CZipArchive zip; - try - { - // compress first to a temporary file, if ok - copy the data, if not - add storing - - if (bEffInMem) - { - pmf = new CZipMemFile; - zip.Open(*pmf, zipCreate); - } - else - zip.Open(szTempFileName, zipCreate); - zip.SetRootPath(m_szRootPath); - zip.SetPassword(GetPassword()); - zip.SetSystemCompatibility(m_iArchiveSystCompatib); - zip.SetCallback(pCallback, cbAdd); - // create a temporary file - int iTempReplaceIndex = info.m_iReplaceIndex; - info.m_iSmartLevel = zipsmLazy; - info.m_iReplaceIndex = -1; - if (!zip.AddNewFile(info)) - throw false; - info.m_iReplaceIndex = iTempReplaceIndex; - - // this may also happen when bReplace, but not in span mode - if (bEff) - { - CZipFileHeader fh; - zip.GetFileInfo(fh, 0); - if (!fh.CompressionEfficient()) - { - info.m_iComprLevel = 0; - info.m_iSmartLevel = zipsmInternal01; - // compression is pointless, store instead - throw AddNewFile(info); - } - } - - m_info.Init(); - throw GetFromArchive(zip, 0, info.m_iReplaceIndex, true, GetCallback(cbAddTmp)); - } - catch (bool bRet) - { - - zip.Close(!bRet); // that doesn't really matter how it will be closed - - if (pmf) - delete pmf; - if (!bEffInMem) - ZipPlatform::RemoveFile(szTempFileName, false); - m_info.ReleaseBuf(); - return bRet; - } - catch (...) - { - zip.Close(true); - - if (pmf) - delete pmf; - if (!bEffInMem) - ZipPlatform::RemoveFile(szTempFileName, false); - m_info.ReleaseBuf(); - throw; - } - } - - // try to open before adding - CZipFile f; - CZipAbstractFile *pf; - if (info.m_pFile) - pf = info.m_pFile; - else - { - if (!f.Open(info.m_szFilePath, CZipFile::modeRead | CZipFile::shareDenyWrite, false)) - { - if (pCallback) - pCallback->CallbackEnd(); - return false; - } - pf = &f; - } - - ASSERT(pf); - // call init before opening (in case of exception we have the names) - iFileSize = pf->GetLength(); - - - bool bRet; - if (bReplace) - { - ASSERT(!bIsCompression); - bRet = OpenNewFile(header, (info.m_iReplaceIndex << 16) | ZIP_COMPR_REPL_SIGN , NULL, iFileSize); - } - else - bRet = OpenNewFile(header, info.m_iComprLevel); - if (!bRet) - { - if (pCallback) - pCallback->CallbackEnd(); - - return false; - } - if (bInternal) - { - // we do it here, because if in OpenNewFile is replacing - // then we get called cbReplace callback before and it would - // overwrite callback information written in pCallback->Init - pCallback = GetCallback(cbAddStore); - if (pCallback) - pCallback->Init(info.m_szFileNameInZip, info.m_szFilePath); - } - if (pCallback) - pCallback->SetTotal(iFileSize); - - CZipAutoBuffer buf(info.m_nBufSize); - DWORD iRead; - int iAborted = 0; - do - { - iRead = pf->Read(buf, info.m_nBufSize); - if (iRead) - { - WriteNewFile(buf, iRead); - if (pCallback) - if (!(*pCallback)(iRead)) - { - // todo: we could remove here the bytes of the file partially added if not disk-spanning - if (iRead == buf.GetSize() && pf->Read(buf, 1) != 0) // test one byte if there is something left - { - if (!m_storage.IsSpanMode() && !bReplace) - { - RemoveLast(true); - CloseNewFile(true); - iAborted = CZipException::abortedSafely; - } - else - iAborted = CZipException::abortedAction; - } - else - { - iAborted = CZipException::abortedSafely; // we did it! - CloseNewFile(); - } - break; - } - - } - - } - while (iRead == buf.GetSize()); - if (!iAborted) - CloseNewFile(); - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - CZipException::Throw(iAborted); // throw to distuinguish from other return codes - - if (bEff) - { - // remove the last file and add it without the compression if needed - if (!info.m_pFile) - f.Close(); - - buf.Release(); - if (RemoveLast()) - { - info.m_iComprLevel = 0; - info.m_iSmartLevel = zipsmInternal01; - return AddNewFile(info); - } - } - return true; - -} - -bool CZipArchive::AddNewFile(CZipAddNewFileInfo& info) -{ - // no need for ASSERT and TRACE here - it will be done by OpenNewFile - - if (!m_info.m_iBufferSize) - return false; - CZipPathComponent::RemoveSeparators(info.m_szFilePath); - if (!info.m_szFilePath.IsEmpty()) // it may be empty after removing sep. - { - if (info.m_szFileNameInZip.IsEmpty()) - { - CZipPathComponent zpc(info.m_szFilePath); - if (info.m_bFullPath) - { - if (m_bRemoveDriveLetter) - info.m_szFileNameInZip = zpc.GetNoDrive(); - } - else - info.m_szFileNameInZip = TrimRootPath(zpc); - } - } - else if (!info.m_pFile) - return false; - - bool bSpan = GetSpanMode() != 0; - - // checking the iReplace index - if (!UpdateReplaceIndex(info.m_iReplaceIndex, info.m_szFileNameInZip)) - return false; - - bool bReplace = info.m_iReplaceIndex >= 0; - - DWORD uAttr; - time_t ttime; - if (info.m_pFile) - { - uAttr = ZipPlatform::GetDefaultAttributes(); - ttime = time(NULL); - } - else - { - if (!ZipPlatform::GetFileAttr(info.m_szFilePath, uAttr)) - return false; // we don't know whether it is a file or a directory - if (!ZipPlatform::GetFileModTime(info.m_szFilePath, ttime)) - ttime = time(NULL); - } - CZipFileHeader header; - header.SetFileName(info.m_szFileNameInZip); - if (ZipPlatform::GetSystemID() != ZipCompatibility::zcUnix) - uAttr |= ZipCompatibility::ConvertToSystem(uAttr, ZipPlatform::GetSystemID(), ZipCompatibility::zcUnix); // make it readable under Unix as well, since it stores its attributes in HIWORD(uAttr) - SetFileHeaderAttr(header, uAttr); - header.SetTime(ttime); - bool bInternal = (info.m_iSmartLevel & zipsmInternal01) != 0; - CZipActionCallback* pCallback = NULL; - if (!bInternal) - { - pCallback = GetCallback(cbAdd); - if (pCallback) - pCallback->Init(info.m_szFileNameInZip, info.m_szFilePath); - } - - - - if (header.IsDirectory()) // will never be when m_pFile is not NULL, so we don't check it - { - ASSERT(!info.m_pFile); // should never happened - ASSERT(!bInternal); - - if (pCallback) - pCallback->SetTotal(0); // in case of calling LeftToDo afterwards - - // clear password for a directory - bool bRet = false; - CZipSmClrPass smcp; - if (info.m_iSmartLevel & zipsmCPassDir) - smcp.ClearPasswordSmartly(this); - - bRet = OpenNewFile(header, bReplace ? (info.m_iReplaceIndex << 16) | ZIP_COMPR_REPL_SIGN : 0); - - CloseNewFile(); - if (pCallback) - pCallback->CallbackEnd(); - - return bRet; - } - - CZipSmClrPass smcp; - bool bIsCompression = info.m_iComprLevel != 0; - bool bEff = (info.m_iSmartLevel & zipsmCheckForEff)&& bIsCompression; - bool bCheckForZeroSized = (info.m_iSmartLevel & zipsmCPFile0) && !GetPassword().IsEmpty(); - bool bCheckForSmallFiles = (info.m_iSmartLevel & zipsmNotCompSmall) && bIsCompression; - DWORD iFileSize = DWORD(-1); - bool bNeedTempArchive = (bEff && bSpan) || (bReplace && bIsCompression); - if (bCheckForSmallFiles || bCheckForZeroSized || bNeedTempArchive) - { - - if (info.m_pFile) - iFileSize = info.m_pFile->GetLength(); - else - { - if (!ZipPlatform::GetFileSize(info.m_szFilePath, iFileSize) && bEff) - bEff = false; // the file size is needed only when eff. in span mode - } - if (iFileSize != DWORD(-1)) - { - if (bCheckForZeroSized && iFileSize == 0) - smcp.ClearPasswordSmartly(this); - if (bCheckForSmallFiles && iFileSize < 5) - info.m_iComprLevel = 0; - } - } - bool bEffInMem = bEff && (info.m_iSmartLevel & zipsmMemoryFlag); - CZipString szTempFileName; - if (bNeedTempArchive && (bEffInMem || - !(szTempFileName = ZipPlatform::GetTmpFileName( - m_szTempPath.IsEmpty() ? NULL : (LPCTSTR)m_szTempPath, iFileSize) - ).IsEmpty())) - { - CZipMemFile* pmf = NULL; - CZipArchive zip; - try - { - // compress first to a temporary file, if ok - copy the data, if not - add storing - - if (bEffInMem) - { - pmf = new CZipMemFile; - zip.Open(*pmf, zipCreate); - } - else - zip.Open(szTempFileName, zipCreate); - zip.SetRootPath(m_szRootPath); - zip.SetPassword(GetPassword()); - zip.SetSystemCompatibility(m_iArchiveSystCompatib); - zip.SetCallback(pCallback, cbAdd); - // create a temporary file - int iTempReplaceIndex = info.m_iReplaceIndex; - info.m_iSmartLevel = zipsmLazy; - info.m_iReplaceIndex = -1; - if (!zip.AddNewFile(info)) - throw false; - info.m_iReplaceIndex = iTempReplaceIndex; - - // this may also happen when bReplace, but not in span mode - if (bEff) - { - CZipFileHeader fh; - zip.GetFileInfo(fh, 0); - if (!fh.CompressionEfficient()) - { - info.m_iComprLevel = 0; - info.m_iSmartLevel = zipsmInternal01; - // compression is pointless, store instead - throw AddNewFile(info); - } - } - - m_info.Init(); - throw GetFromArchive(zip, 0, info.m_iReplaceIndex, true, GetCallback(cbAddTmp)); - } - catch (bool bRet) - { - - zip.Close(!bRet); // that doesn't really matter how it will be closed - if (pmf) - delete pmf; - if (!bEffInMem) - ZipPlatform::RemoveFile(szTempFileName, false); - m_info.ReleaseBuf(); - return bRet; - } - catch (...) - { - zip.Close(true); - if (pmf) - delete pmf; - if (!bEffInMem) - ZipPlatform::RemoveFile(szTempFileName, false); - m_info.ReleaseBuf(); - throw; - } - } - - // try to open before adding - CZipFile f; - CZipAbstractFile *pf; - if (info.m_pFile) - pf = info.m_pFile; - else - { - // cannot be shareDenyWrite - // from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/creating_and_opening_files.asp : - // If you specify the GENERIC_READ and GENERIC_WRITE access modes along with the FILE_SHARE_READ and FILE_SHARE_WRITE sharing modes in your first call to CreateFile. If you specify the GENERIC_READ and GENERIC_WRITE access modes and the FILE_SHARE_READ sharing mode only in your second call to CreateFile, the function will fail with a sharing violation because the read-only sharing mode specified in the second call conflicts with the read/write access that has been granted in the first call. - if (!f.Open(info.m_szFilePath, CZipFile::modeRead | CZipFile::shareDenyNone, false)) - { - if (pCallback) - pCallback->CallbackEnd(); - return false; - } - pf = &f; - } - - ASSERT(pf); - // call init before opening (in case of exception we have the names) - iFileSize = pf->GetLength(); - - - bool bRet; - if (bReplace) - { - ASSERT(!bIsCompression); - bRet = OpenNewFile(header, (info.m_iReplaceIndex << 16) | ZIP_COMPR_REPL_SIGN , NULL, iFileSize); - } - else - bRet = OpenNewFile(header, info.m_iComprLevel); - if (!bRet) - { - if (pCallback) - pCallback->CallbackEnd(); - - return false; - } - if (bInternal) - { - // we do it here, because if in OpenNewFile is replacing - // then we get called cbReplace callback before and it would - // overwrite callback information written in pCallback->Init - pCallback = GetCallback(cbAddStore); - if (pCallback) - pCallback->Init(info.m_szFileNameInZip, info.m_szFilePath); - } - if (pCallback) - pCallback->SetTotal(iFileSize); - - CZipAutoBuffer buf(info.m_nBufSize); - DWORD iRead; - int iAborted = 0; - do - { - iRead = pf->Read(buf, info.m_nBufSize); - if (iRead) - { - WriteNewFile(buf, iRead); - if (pCallback) - if (!(*pCallback)(iRead)) - { - // todo: we could remove here the bytes of the file partially added if not disk-spanning - if (iRead == buf.GetSize() && pf->Read(buf, 1) != 0) // test one byte if there is something left - { - if (!m_storage.IsSpanMode() && !bReplace) - { - RemoveLast(true); - CloseNewFile(true); - iAborted = CZipException::abortedSafely; - } - else - iAborted = CZipException::abortedAction; - } - else - { - iAborted = CZipException::abortedSafely; // we did it! - CloseNewFile(); - } - break; - } - - } - - } - while (iRead == buf.GetSize()); - if (!iAborted) - CloseNewFile(); - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - CZipException::Throw(iAborted); // throw to distuinguish from other return codes - - if (bEff) - { - // remove the last file and add it without the compression if needed - if (!info.m_pFile) - f.Close(); - - buf.Release(); - if (RemoveLast()) - { - info.m_iComprLevel = 0; - info.m_iSmartLevel = zipsmInternal01; - return AddNewFile(info); - } - } - return true; - -} - -bool CZipArchive::RemoveLast(bool bRemoveAnyway) -{ - int iIndex = GetCount() - 1; - if (iIndex < 0) - return false; - CZipFileHeader* pHeader = m_centralDir[iIndex]; - - if (!bRemoveAnyway && pHeader->CompressionEfficient()) - return false; - - m_centralDir.RemoveLastFile(pHeader, iIndex); - return true; -} - - - - -CZipString CZipArchive::GetArchivePath() const -{ - if (IsClosed(false)) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return _T(""); - } - return m_storage.m_pFile->GetFilePath(); -} - -CZipString CZipArchive::GetGlobalComment() const -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return _T(""); - } - CZipString temp; - return SingleToWide(m_centralDir.m_pszComment, temp) != -1 ? (LPCTSTR)temp : _T(""); -} - -bool CZipArchive::SetGlobalComment(LPCTSTR lpszComment) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - if (m_storage.IsSpanMode() == -1) - { - TRACE(_T("%s(%i) : You cannot modify the global comment of the existing disk spanning archive.\n"),__FILE__,__LINE__); - return false; - } - - WideToSingle(lpszComment, m_centralDir.m_pszComment); - m_centralDir.RemoveFromDisk(); - if (m_bAutoFlush) - Flush(); - - return true; -} - - - -int CZipArchive::GetCurrentDisk() const -{ - return m_storage.GetCurrentDisk() + 1; -} - -bool CZipArchive::SetFileComment(WORD uIndex, LPCTSTR lpszComment) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - if (m_storage.IsSpanMode() == -1) - { - TRACE(_T("%s(%i) : You cannot modify the file comment in the existing disk spanning archive.\n"),__FILE__,__LINE__); - return false; - } - - if (!m_centralDir.IsValidIndex(uIndex)) - { - ASSERT(FALSE); - return false; - } - m_centralDir[uIndex]->SetComment(lpszComment); - m_centralDir.RemoveFromDisk(); - if (m_bAutoFlush) - Flush(); - return true; -} - - -void CZipArchive::CryptInitKeys() -{ - ASSERT(m_pszPassword.GetSize()); - m_keys[0] = 305419896L; - m_keys[1] = 591751049L; - m_keys[2] = 878082192L; - for (DWORD i = 0; i < m_pszPassword.GetSize(); i++) - CryptUpdateKeys(m_pszPassword[i]); -} - -void CZipArchive::CryptUpdateKeys(char c) -{ - - m_keys[0] = CryptCRC32(m_keys[0], c); - m_keys[1] += m_keys[0] & 0xff; - m_keys[1] = m_keys[1] * 134775813L + 1; - c = char(m_keys[1] >> 24); - m_keys[2] = CryptCRC32(m_keys[2], c); -} - -bool CZipArchive::CryptCheck() -{ - CZipAutoBuffer buf(ZIPARCHIVE_ENCR_HEADER_LEN); - m_storage.Read(buf, ZIPARCHIVE_ENCR_HEADER_LEN, false); - BYTE b = 0; - for (int i = 0; i < ZIPARCHIVE_ENCR_HEADER_LEN; i++) - { - b = buf[i]; // only temporary - CryptDecode((char&)b); - } - // check the last byte - return CurrentFile()->IsDataDescr() ? - (BYTE(CurrentFile()->m_uModTime >> 8) == b) : (BYTE(CurrentFile()->m_uCrc32 >> 24) == b); -} - -char CZipArchive::CryptDecryptByte() -{ - int temp = (m_keys[2] & 0xffff) | 2; - return (char)(((temp * (temp ^ 1)) >> 8) & 0xff); -} - -void CZipArchive::CryptDecode(char &c) -{ - c ^= CryptDecryptByte(); - CryptUpdateKeys(c); -} - -bool CZipArchive::SetPassword(LPCTSTR lpszPassword) -{ - if (m_iFileOpened != nothing) - { - TRACE(_T("%s(%i) : You cannot change the password when the file is opened.\n"),__FILE__,__LINE__); - return false; // it's important not to change the password when the file inside archive is opened - } - if (IsClosed()) - { - TRACE(_T("%s(%i) : Setting the password for a closed archive has no effect.\n"),__FILE__,__LINE__); - } - if (lpszPassword) - { - int iLen = WideToSingle(lpszPassword, m_pszPassword); - if (iLen == -1) - return false; - for (size_t i = 0; (int)i < iLen; i++) - if (m_pszPassword[i] <= 0) - { - m_pszPassword.Release(); - TRACE(_T("%s(%i) : The password contains forbidden characters. Password cleared.\n"),__FILE__,__LINE__); - return false; - } - } - else - m_pszPassword.Release(); - return true; -} - -CZipString CZipArchive::GetPassword()const -{ - CZipString temp; - CZipArchive::SingleToWide(m_pszPassword, temp); - return temp; -} - -DWORD CZipArchive::CryptCRC32(DWORD l, char c) -{ - const DWORD *CRC_TABLE = get_crc_table(); - return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8); -} - -void CZipArchive::CryptCryptHeader(long iCrc, CZipAutoBuffer &buf) -{ - CryptInitKeys(); - srand(UINT(time(NULL))); - // genereate pseudo-random sequence - char c; - for (int i = 0; i < ZIPARCHIVE_ENCR_HEADER_LEN - 2; i++) - { - int t1 = rand(); - c = (char)(t1 >> 6); - if (!c) - c = (char)t1; - CryptEncode(c); - buf[i] = c; - - } - c = (char)((iCrc >> 16) & 0xff); - CryptEncode(c); - buf[ZIPARCHIVE_ENCR_HEADER_LEN - 2] = c; - c = (char)((iCrc >> 24) & 0xff); - CryptEncode(c); - buf[ZIPARCHIVE_ENCR_HEADER_LEN - 1] = c; -} - -void CZipArchive::CryptEncode(char &c) -{ - char t = CryptDecryptByte(); - CryptUpdateKeys(c); - c ^= t; -} - -void CZipArchive::CryptEncodeBuffer() -{ - if (CurrentFile()->IsEncrypted()) - for (DWORD i = 0; i < m_info.m_uComprLeft; i++) - CryptEncode(m_info.m_pBuffer[i]); -} - -void CZipArchive::CloseFileAfterTestFailed() -{ - if (m_iFileOpened != extract) - { - TRACE(_T("%s(%i) : No file opened.\n"),__FILE__,__LINE__); - return; - } - m_info.ReleaseBuf(); - m_centralDir.Clear(false); - m_iFileOpened = nothing; -} - -bool CZipArchive::TestFile(WORD uIndex, DWORD uBufSize) -{ - if (m_storage.IsSpanMode() == 1) - { - TRACE(_T("%s(%i) : You cannot test the spanning archive in creation.\n"),__FILE__,__LINE__); - return false; - } - if (!uBufSize) - return false; - - CZipFileHeader* pHeader = m_centralDir[uIndex]; - CZipActionCallback* pCallback = GetCallback(cbTest); - if (pCallback) - { - pCallback->Init(m_centralDir.GetProperHeaderFileName(pHeader)); - } - - if (pHeader->IsDirectory()) - { - if (pCallback) - pCallback->SetTotal(0); - - // we do not test whether the password for the encrypted directory - // is correct, since it seems to be senseless (anyway password - // encrypted directories should be avoided - it adds 12 bytes) - DWORD iSize = pHeader->m_uComprSize; - if ((iSize != 0 || iSize != pHeader->m_uUncomprSize) - // different treating compressed directories - && !(pHeader->IsEncrypted() && iSize == 12 && !pHeader->m_uUncomprSize)) - CZipException::Throw(CZipException::dirWithSize); - - if (pCallback) - pCallback->CallbackEnd(); - - return true; - } - else - { - try - { - if (pCallback) - pCallback->SetTotal(pHeader->m_uUncomprSize); - - if (!OpenFile(uIndex)) - return false; - CZipAutoBuffer buf(uBufSize); - DWORD iRead; - int iAborted = 0; - do - { - iRead = ReadFile(buf, buf.GetSize()); - if (pCallback && iRead) - if (!(*pCallback)(iRead)) - { - if (iRead == buf.GetSize() && ReadFile(buf, 1) != 0) // test one byte if there is something left - iAborted = CZipException::abortedAction; - else - iAborted = CZipException::abortedSafely; // we did it! - break; - } - } - while (iRead == buf.GetSize()); - bool bRet = CloseFile() != -1; - if (!bRet && iAborted == CZipException::abortedSafely) - iAborted = CZipException::abortedAction; // sorry, finished, but not successfull - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - CZipException::Throw(iAborted); // throw to distuingiush from other return codes - if (bRet) - return true; - else - CZipException::Throw(CZipException::badZipFile); - return false; // to satisfy the compiler and eliminate warning - } - catch(...) - { - CloseFileAfterTestFailed(); - throw; - } - } -} - -int CZipArchive::WideToSingle(LPCTSTR lpWide, CZipAutoBuffer &szSingle) -{ -#ifdef _UNICODE - return ZipPlatform::WideToSingle(lpWide, szSingle); -#else - - size_t iLen = strlen(lpWide); - // if not UNICODE just copy - // iLen does not include the NULL character - szSingle.Allocate(iLen); - memcpy(szSingle, lpWide, iLen); - return iLen; -#endif - -} - -int CZipArchive::SingleToWide(const CZipAutoBuffer &szSingle, CZipString& szWide) -{ - -#ifdef _UNICODE - return ZipPlatform::SingleToWide(szSingle, szWide); -#else // if not UNICODE just copy - int singleLen = szSingle.GetSize(); - // iLen does not include the NULL character - memcpy(szWide.GetBuffer(singleLen),szSingle.GetBuffer(), singleLen); - szWide.ReleaseBuffer(singleLen); - return singleLen; -#endif -} - -void CZipArchive::CryptDecodeBuffer(DWORD uCount) -{ - if (CurrentFile()->IsEncrypted()) - for (DWORD i = 0; i < uCount; i++) - CryptDecode(m_info.m_pBuffer[i]); -} - -void CZipArchive::EmptyPtrList() -{ - if (m_list.GetCount()) - { - // if some memory hasn't been freed due to an error in zlib, so free it now - CZipPtrListIter iter = m_list.GetHeadPosition(); - while (m_list.IteratorValid(iter)) - delete[] (char*) m_list.GetNext(iter); - } - m_list.RemoveAll(); -} - - - -void CZipArchive::SetFileHeaderAttr(CZipFileHeader& header, DWORD uAttr) -{ - header.SetSystemCompatibility(m_iArchiveSystCompatib); - header.SetSystemAttr(uAttr); -} - -void CZipArchive::EnableFindFast(bool bEnable) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : Set it after opening the archive.\n"),__FILE__,__LINE__); - return; - } - m_centralDir.EnableFindFast(bEnable, m_bCaseSensitive); - -} - -bool CZipArchive::SetSystemCompatibility(int iSystemComp) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : Set it after opening the archive.\n"),__FILE__,__LINE__); - return false; - } - - if (m_iFileOpened == compress) - { - TRACE(_T("%s(%i) : Set it before opening a file inside archive.\n"),__FILE__,__LINE__); - return false; - } - - if (!ZipCompatibility::IsPlatformSupported(iSystemComp)) - return false; - m_iArchiveSystCompatib = iSystemComp; - return true; -} - -void CZipArchive::SetRootPath(LPCTSTR szPath) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : Set it after opening the archive.\n"),__FILE__,__LINE__); - return; - } - - if (m_iFileOpened != nothing) - { - TRACE(_T("%s(%i) : Set it before opening a file inside archive.\n"),__FILE__,__LINE__); - return; - } - - if (szPath) - { - m_szRootPath = szPath; - CZipPathComponent::RemoveSeparators(m_szRootPath); - } - else - m_szRootPath.Empty(); -} - -CZipString CZipArchive::TrimRootPath(CZipPathComponent &zpc)const -{ - if (m_szRootPath.IsEmpty()) - return zpc.GetFileName(); - CZipString szPath = zpc.GetFullPath(); - return RemovePathBeginning(m_szRootPath, szPath, m_pZipCompare) ? szPath : zpc.GetFileName(); -} - -bool CZipArchive::RemovePathBeginning(LPCTSTR lpszBeginning, CZipString& szPath, ZIPSTRINGCOMPARE pCompareFunction) -{ - CZipString szBeginning(lpszBeginning); - CZipPathComponent::RemoveSeparators(szBeginning); - int iRootPathLength = szBeginning.GetLength(); - if (iRootPathLength && szPath.GetLength() >= iRootPathLength && - (szPath.Left(iRootPathLength).*pCompareFunction)(szBeginning) == 0) - { - // the beginning is the same - if (szPath.GetLength() == iRootPathLength) - { - szPath.Empty(); - return true; - } - // is the end of m_szPathRoot only a beginning of a directory name? - // check for a separator - // we know the length is larger, so we can write: - if (CZipPathComponent::IsSeparator(szPath[iRootPathLength])) - { - szPath = szPath.Mid(iRootPathLength); - CZipPathComponent::RemoveSeparatorsLeft(szPath); - return true; - } - } - return false; -} - -void CZipArchive::SetTempPath(LPCTSTR lpszPath, bool bForce) -{ - m_szTempPath = lpszPath; - if (lpszPath && bForce) - ZipPlatform::ForceDirectory(lpszPath); - CZipPathComponent::RemoveSeparators(m_szTempPath); -} - -CZipString CZipArchive::PredictFileNameInZip(LPCTSTR lpszFilePath, - bool bFullPath, int iWhat, bool bExactly)const -{ - CZipString sz = lpszFilePath; - if (sz.IsEmpty()) - return _T(""); - bool bAppend; - switch (iWhat) - { - case prFile: - bAppend = false; - break; - case prDir: - bAppend = true; - break; - default: - bAppend = CZipPathComponent::IsSeparator(sz[sz.GetLength() - 1]); - } - - // remove for CZipPathComponent treating last name as a file even if dir - CZipPathComponent::RemoveSeparators(sz); - CZipPathComponent zpc(sz); - - if (bFullPath) - { - if (m_bRemoveDriveLetter) - sz = zpc.GetNoDrive(); - } - else - sz = TrimRootPath(zpc); - - if (bAppend && !sz.IsEmpty()) - CZipPathComponent::AppendSeparator(sz); - CZipFileHeader fh; // create a temporary object to convert - fh.SetFileName(sz); - if (bExactly) - { - fh.SetSystemCompatibility(m_iArchiveSystCompatib); - ZipCompatibility::FileNameUpdate(fh, false); - } - else - { - fh.SetSystemCompatibility(-1); // non existing system to prevent ansi oem conversion - ZipCompatibility::FileNameUpdate(fh, true);// update only path separators - } - - return fh.GetFileName(); -} - -CZipString CZipArchive::PredictExtractedFileName(LPCTSTR lpszFileNameInZip, LPCTSTR lpszPath, bool bFullPath, LPCTSTR lpszNewName)const -{ - CZipString szFile = lpszPath; - CZipString sz = lpszNewName ? lpszNewName : lpszFileNameInZip; - if (sz.IsEmpty()) - return szFile; - if (!szFile.IsEmpty()) - CZipPathComponent::AppendSeparator(szFile); - - - // remove for CZipPathComponent treating last name as a file even if dir - CZipPathComponent::RemoveSeparators(sz); - CZipPathComponent zpc(sz); - szFile += bFullPath ? (m_bRemoveDriveLetter ? zpc.GetNoDrive() : sz) - : TrimRootPath(zpc); - return szFile; -} - - -void CZipArchive::SetAutoFlush(bool bAutoFlush) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive not yet opened.\n"),__FILE__,__LINE__); - return; - } - if (m_storage.IsSpanMode() != 0) - { - TRACE(_T("%s(%i) : Cannot set auto-flush for the disk spanning archive.\n"),__FILE__,__LINE__); - return; - } - m_bAutoFlush = bAutoFlush; -} - -void CZipArchive::Flush() -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive not yet opened.\n"),__FILE__,__LINE__); - return; - } - - if (m_storage.IsSpanMode() < 0) - { - TRACE(_T("%s(%i) : Cannot flush an existing disk spanning archive.\n"),__FILE__,__LINE__); - return; - } - WriteCentralDirectory(); - m_storage.FlushFile(); - if (m_storage.IsSpanMode() > 0) // try to finalize disk-spanning archive without closing it - m_storage.FinalizeSpan(); -} - - -void CZipArchive::GetCentralDirInfo(CZipCentralDir::Info& info)const -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive not yet opened.\n"),__FILE__,__LINE__); - return; - - } - m_centralDir.GetInfo(info); - if (GetSpanMode() > 0) - info.m_uDiskEntriesNo = m_storage.GetCurrentDisk(); -} - -bool CZipArchive::CWildcard::IsPatternValid(LPCTSTR lpszPattern, int* iErrorType) -{ - try - { - /* loop through pattern to EOS */ - while (*lpszPattern) - { - /* determine pattern type */ - switch (*lpszPattern) - { - /* check literal escape, it cannot be at end of pattern */ - case _T('\\'): - if (!*++lpszPattern) - throw patternEsc; - lpszPattern++; - break; - - /* the [..] construct must be well formed */ - case _T('['): - lpszPattern++; - - /* if the next character is ']' then bad pattern */ - if (*lpszPattern == _T(']')) - throw patternEmpty; - - /* if end of pattern here then bad pattern */ - if (!*lpszPattern) - throw patternClose; - - /* loop to end of [..] construct */ - while (*lpszPattern != _T(']')) - { - /* check for literal escape */ - if (*lpszPattern == _T('\\')) - { - lpszPattern++; - - /* if end of pattern here then bad pattern */ - if (!*lpszPattern++) - throw patternEsc; - } - else lpszPattern++; - - /* if end of pattern here then bad pattern */ - if (!*lpszPattern) - throw patternClose; - - /* if this a range */ - if (*lpszPattern == _T('-')) - { - /* we must have an end of range */ - if (!*++lpszPattern || *lpszPattern == ']') - throw patternRange; - else - { - - /* check for literal escape */ - if (*lpszPattern == _T('\\')) - lpszPattern++; - - /* if end of pattern here - then bad pattern */ - if (!*lpszPattern++) - throw patternEsc; - } - } - } - break; - - /* all other characters are valid pattern elements */ - case '*': - case '?': - default: - lpszPattern++; /* "normal" character */ - break; - } - } - throw patternValid; - } - catch (int i) - { - if (iErrorType) - *iErrorType = i; - return i == patternValid; - } - - -} - -bool CZipArchive::CWildcard::IsPattern(LPCTSTR lpszPattern) -{ - while (*lpszPattern) - { - switch (*lpszPattern++) - { - case _T('?'): - case _T('*'): - case _T('['): - case _T('\\'): - return true; - } - } - return false; - -} - -bool CZipArchive::CWildcard::IsMatch(LPCTSTR lpszText, int *iRetCode) -{ - CZipString sz; - if (!m_bCaseSensitive) - { - sz = lpszText; - sz.MakeLower(); - lpszText = (LPCTSTR)sz; - } - int i = Match((LPCTSTR)m_szPattern, lpszText); - if (iRetCode) - *iRetCode = i; - return i == matchValid; -} - -int CZipArchive::CWildcard::MatchAfterStar(LPCTSTR p, LPCTSTR t) -{ - int iMatch = matchNone; - TCHAR nextp; - - /* pass over existing ? and * in pattern */ - - while ( *p == _T('?') || *p == _T('*') ) - { - /* take one char for each ? and + */ - - if (*p == _T('?')) - { - /* if end of text then no match */ - if (!*t++) - return matchAbort; - } - - /* move to next char in pattern */ - - p++; - } - - /* if end of pattern we have matched regardless of text left */ - - if (!*p) - return matchValid; - - /* get the next character to match which must be a literal or '[' */ - - nextp = *p; - if (nextp == _T('\\')) - { - nextp = p[1]; - - /* if end of text then we have a bad pattern */ - - if (!nextp) - return matchPattern; - } - - /* Continue until we run out of text or definite result seen */ - - do - { - /* a precondition for matching is that the next character - in the pattern match the next character in the text or that - the next pattern char is the beginning of a range. Increment - text pointer as we go here */ - - if (nextp == *t || nextp == _T('[')) - iMatch = Match(p, t); - - /* if the end of text is reached then no iMatch */ - - if (!*t++) - iMatch = matchAbort; - - } while ( iMatch != matchValid && - iMatch != matchAbort && - iMatch != matchPattern); - - /* return result */ - - return iMatch; -} - - -int CZipArchive::CWildcard::Match(LPCTSTR lpszPattern, LPCTSTR lpszText) -{ - - TCHAR range_start, range_end; /* start and end in range */ - - bool bInvert; /* is this [..] or [!..] */ - bool bMemberMatch; /* have I matched the [..] construct? */ - bool bLoop; /* should I terminate? */ - - for ( ; *lpszPattern; lpszPattern++, lpszText++) - { - /* if this is the end of the text - then this is the end of the match */ - - if (!*lpszText) - { - if ( *lpszPattern == _T('*') && *++lpszPattern == _T('\0') ) - return matchValid; - else - return matchAbort; - } - - /* determine and react to pattern type */ - - switch (*lpszPattern) - { - case _T('?'): /* single any character match */ - break; - - case _T('*'): /* multiple any character match */ - return MatchAfterStar (lpszPattern, lpszText); - - /* [..] construct, single member/exclusion character match */ - case _T('['): - { - /* move to beginning of range */ - - lpszPattern++; - - /* check if this is a member match or exclusion match */ - - bInvert = false; - if (*lpszPattern == _T('!') || *lpszPattern == _T('^')) - { - bInvert = true; - lpszPattern++; - } - - /* if closing bracket here or at range start then we have a - malformed pattern */ - - if (*lpszPattern == _T(']')) - return matchPattern; - - bMemberMatch = false; - bLoop = true; - - while (bLoop) - { - /* if end of construct then bLoop is done */ - - if (*lpszPattern == _T(']')) - { - bLoop = false; - continue; - } - - /* matching a '!', '^', '-', '\' or a ']' */ - - if (*lpszPattern == _T('\\')) - range_start = range_end = *++lpszPattern; - else - range_start = range_end = *lpszPattern; - - /* if end of pattern then bad pattern (Missing ']') */ - - if (!*lpszPattern) - return matchPattern; - - /* check for range bar */ - if (*++lpszPattern == _T('-')) - { - /* get the range end */ - - range_end = *++lpszPattern; - - /* if end of pattern or construct - then bad pattern */ - - if (range_end == _T('\0') || range_end == _T(']')) - return matchPattern; - /* special character range end */ - if (range_end == _T('\\')) - { - range_end = *++lpszPattern; - - /* if end of text then - we have a bad pattern */ - if (!range_end) - return matchPattern; - } - - /* move just beyond this range */ - lpszPattern++; - } - - /* if the text character is in range then match found. - make sure the range letters have the proper - relationship to one another before comparison */ - - if (range_start < range_end) - { - if (*lpszText >= range_start && *lpszText <= range_end) - { - bMemberMatch = true; - bLoop = false; - } - } - else - { - if (*lpszText >= range_end && *lpszText <= range_start) - { - bMemberMatch = true; - bLoop = false; - } - } - } - - /* if there was a match in an exclusion set then no match */ - /* if there was no match in a member set then no match */ - - if ((bInvert && bMemberMatch) || !(bInvert || bMemberMatch)) - return matchRange; - - /* if this is not an exclusion then skip the rest of - the [...] construct that already matched. */ - - if (bMemberMatch) - { - while (*lpszPattern != _T(']')) - { - /* bad pattern (Missing ']') */ - if (!*lpszPattern) - return matchPattern; - - /* skip exact match */ - if (*lpszPattern == _T('\\')) - { - lpszPattern++; - - /* if end of text then - we have a bad pattern */ - - if (!*lpszPattern) - return matchPattern; - } - - /* move to next pattern char */ - - lpszPattern++; - } - } - break; - } - case _T('\\'): /* next character is quoted and must match exactly */ - - /* move pattern pointer to quoted char and fall through */ - - lpszPattern++; - - /* if end of text then we have a bad pattern */ - - if (!*lpszPattern) - return matchPattern; - - /* must match this character exactly */ - - default: - if (*lpszPattern != *lpszText) - return matchPattern; - } - } - /* if end of text not reached then the pattern fails */ - - if (*lpszText) - return matchEnd; - else - return matchValid; -} - -void CZipArchive::FindMatches(LPCTSTR lpszPattern, CZipWordArray &ar, bool bFullPath) const -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return; - } - - // ar.RemoveAll(); don't do this - int iCount = GetCount(); - CWildcard wc(lpszPattern, m_bCaseSensitive); - for (int i = 0; i < iCount; i++) - { - const CZipFileHeader* pHeader = m_centralDir[i]; - CZipString sz = m_centralDir.GetProperHeaderFileName(pHeader); - if (!bFullPath) - { - CZipPathComponent::RemoveSeparators(sz); - CZipPathComponent zpc(sz); - sz = zpc.GetFileName(); - } - if (wc.IsMatch(sz)) - ar.Add(i); - } -} - -int CZipArchive::WillBeDuplicated(LPCTSTR lpszFilePath, bool bFullPath, bool bFileNameOnly , int iWhat) -{ - CZipString szFile; - // we predict with bExactly set to false, because FindFile converts all filanames anyway - if (bFileNameOnly) - { - CZipPathComponent zpc(lpszFilePath); - szFile = PredictFileNameInZip(zpc.GetFileName(), false, iWhat); - } - else - szFile = PredictFileNameInZip(lpszFilePath, bFullPath, iWhat); - return FindFile(szFile, ffDefault, bFileNameOnly); -} - - -// it'll get up to the next file or to the end of file (bad if zip corrupted or not-ordered by offsett or redundant bytes added) -bool CZipArchive::GetFromArchive(CZipArchive& zip, WORD uIndex, int iReplaceIndex, bool bKeepSystComp, CZipActionCallback* pCallback) -{ - - if (IsClosed() || zip.IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - - if (m_iFileOpened || zip.m_iFileOpened) - { - TRACE(_T("%s(%i) : You cannot get files from another archive if there is a file opened.\n"),__FILE__,__LINE__); - return false; - } - - if (zip.m_storage.IsSpanMode()) - { - TRACE(_T("%s(%i) : You cannot get files from the disk spannig archive.\n"),__FILE__,__LINE__); - return false; - } - - if (m_storage.IsSpanMode() == -1) - { - TRACE(_T("%s(%i) : You cannot add files to the existing disk spannig archive.\n"),__FILE__,__LINE__); - return false; - } - - ASSERT(m_info.m_pBuffer.GetSize() > 0); - - bool bIsSpan = m_storage.IsSpanMode() == 1; - - CZipFileHeader fh; - if (!zip.GetFileInfo(fh, uIndex)) - return false; - CZipAbstractFile* pFile = zip.m_storage.m_pFile; - - - DWORD uEndOffset; - if (uIndex < zip.GetCount() - 1) - { - CZipFileHeader fhTemp; - if (!zip.GetFileInfo(fhTemp, uIndex+1)) - return false; - uEndOffset = fhTemp.m_uOffset; - } - else - { - CZipCentralDir::Info info; - zip.m_centralDir.GetInfo(info); - if (info.m_bOnDisk) - uEndOffset = info.m_uOffset; - else - uEndOffset = pFile->GetLength(); - } - uEndOffset += zip.m_centralDir.GetBytesBefore(); - DWORD uStartOffset = zip.m_centralDir.GetBytesBefore() + fh.m_uOffset + fh.GetSize(true); - DWORD uTotalToMove = uEndOffset - uStartOffset, uTotalMoved = 0; - - DWORD uPredictedSize = fh.m_uComprSize + - (fh.IsDataDescr() ? ZIPARCHIVE_DATADESCRIPTOR_LEN : 0); - if (uTotalToMove > uPredictedSize + 4/* may be or may be not a signature*/) - uTotalToMove = uPredictedSize + 4; - else if (uTotalToMove < uPredictedSize) - ThrowError(CZipException::badZipFile); - - // conversion stuff - CZipString szFileNameConverted, szFileName; - bool bConvertSystem = !bKeepSystComp && fh.GetSystemCompatibility() != m_iArchiveSystCompatib; - - // GetFileInfo always converts the filename regardless of zip.m_centralDir.m_bConvertAfterOpen value - szFileNameConverted = fh.GetFileName(); - if (bConvertSystem) - { - DWORD uAttr = fh.GetSystemAttr(); - fh.SetSystemCompatibility(m_iArchiveSystCompatib); - fh.SetSystemAttr(uAttr); - } - - ZipCompatibility::FileNameUpdate(fh, false); - szFileName = fh.GetFileName(); - - - bool bNeedDataDescr = bIsSpan && !fh.IsDataDescr(); - if (bNeedDataDescr) - fh.m_uFlag |= 8; // data descriptor present - - - // needed by InsertFindFastElement - if (m_centralDir.IsFindFastEnabled()) - fh.SetFileName(szFileNameConverted); - - - if (!UpdateReplaceIndex(iReplaceIndex, szFileNameConverted)) - return false; - - bool bReplace = iReplaceIndex >= 0; - int iCallbackType = 0; - if (pCallback) - iCallbackType = pCallback->m_iType; - - // if the same callback is applied to cbReplace, then the previous information about the type will be lost - CZipFileHeader* pHeader = m_centralDir.AddNewFile(fh, iReplaceIndex); // must be converted when adding because of InsertFastElement - if (bReplace) - MakeSpaceForReplace(iReplaceIndex, uTotalToMove + fh.GetSize(true), szFileNameConverted); - - if (pCallback) - { - pCallback->m_iType = iCallbackType; - pCallback->Init(szFileNameConverted, zip.GetArchivePath()); - pCallback->SetTotal(fh.m_uComprSize); - } - - if (m_centralDir.IsFindFastEnabled()) - pHeader->SetFileName(szFileName); - - // must be written as not converted - pHeader->WriteLocal(m_storage); - - // made a correction to what was set in WriteLocal - pHeader->m_uOffset -= m_centralDir.GetBytesBefore(); - - // we keep in converted in memory - if (m_centralDir.m_bConvertAfterOpen) - pHeader->SetFileName(szFileNameConverted); - - - // skip reading the local file header - - pFile->Seek(uStartOffset, CZipAbstractFile::begin); - - - DWORD uPack = uTotalToMove > m_info.m_pBuffer.GetSize() ? m_info.m_pBuffer.GetSize() : uTotalToMove; - char* buf = (char*)m_info.m_pBuffer; - - DWORD size_read; - - int iAborted = 0; - bool bBreak = false; - if (uPack) - do - { - size_read = pFile->Read(buf, uPack); - if (!size_read) - break; - if (uTotalMoved + size_read > uTotalToMove) - { - size_read = uTotalToMove - uTotalMoved; - if (!size_read) // this is for protection - break; - bBreak = true; - } - - m_storage.Write(buf, size_read, false); - uTotalMoved += size_read; - if (pCallback) - if (!(*pCallback)(size_read)) - { - if (uTotalToMove != uTotalMoved) - { - if (!bIsSpan && !bReplace) - { - m_centralDir.RemoveLastFile(); - iAborted = CZipException::abortedSafely; - } - else - iAborted = CZipException::abortedAction; - } - else - iAborted = CZipException::abortedSafely; // we did it! - break; - - } - } - while (!bBreak); - - if (iAborted) - CZipException::Throw(iAborted); // throw to distuingiush from other return codes - - // copying from non-span to span or from span without data description to span - // so add the data descriptor - - m_centralDir.m_pOpenedFile = NULL; - if (bNeedDataDescr && uTotalMoved == uTotalToMove) - { - const int iToWrite = ZIPARCHIVE_DATADESCRIPTOR_LEN + 4; - CZipAutoBuffer buf(iToWrite); - memcpy(buf, m_storage.m_gszExtHeaderSignat, 4); - pHeader->GetCrcAndSizes(buf + 4); - m_storage.Write(buf, iToWrite, true); - - } - m_storage.Flush(); - if (uTotalMoved < uTotalToMove) - ThrowError(CZipException::badZipFile); - - - if (pCallback) - pCallback->CallbackEnd(); - - return true; -} - -bool CZipArchive::GetFromArchive(CZipArchive& zip, CZipWordArray &aIndexes, bool bKeepSystComp) -{ - aIndexes.Sort(true); - int iFiles = aIndexes.GetSize(); - m_info.Init(); - try - { - for (int i = 0; i < iFiles; i++) - { - int iFileIndex = aIndexes[i]; - if (!m_centralDir.IsValidIndex(iFileIndex)) - if (!GetFromArchive(zip, iFileIndex, -1, bKeepSystComp, GetCallback(cbGetFromArchive))) - { - m_info.ReleaseBuf(); - return false; - } - } - } - catch (...) - { - m_info.ReleaseBuf(); - throw; - } - m_info.ReleaseBuf(); - if (m_bAutoFlush) - Flush(); - return true; -} -bool CZipArchive::RenameFile(WORD uIndex, LPCTSTR lpszNewName) -{ - if (IsClosed()) - { - TRACE(_T("%s(%i) : ZipArchive is closed.\n"),__FILE__,__LINE__); - return false; - } - - if (m_storage.IsSpanMode()) - { - TRACE(_T("%s(%i) : You cannot rename files in the disk spannig archive.\n"),__FILE__,__LINE__); - return false; - } - - if (m_iFileOpened) - { - TRACE(_T("%s(%i) : You cannot rename a file if there is a file opened.\n"),__FILE__,__LINE__); - return false; - } - CZipFileHeader fh, fhNew; - if (!GetFileInfo(fh, uIndex)) - return false; - CZipString szNewName(lpszNewName); - if (fh.IsDirectory()) - CZipPathComponent::AppendSeparator(szNewName); - else - CZipPathComponent::RemoveSeparators(szNewName); - if (fh.GetFileName().Collate(szNewName) == 0) - return true; - fhNew.SetSystemCompatibility(m_iArchiveSystCompatib); - - fhNew.SetFileName(szNewName); - ZipCompatibility::FileNameUpdate(fhNew, false); - ZipCompatibility::FileNameUpdate(fh, false); // in case the conversion changes the filename size - WORD uFileNameLen = fh.GetFileNameSize(); - WORD uNewFileNameLen = fhNew.GetFileNameSize(); - int iDelta = uNewFileNameLen - uFileNameLen; - int iOffset = 0; - CZipAutoBuffer buf, *pBuf; - m_centralDir.RemoveFromDisk(); // does m_storage.Flush(); - if (iDelta != 0) - { - // we need to make more or less space - - m_info.Init(); - DWORD uStartOffset = fh.m_uOffset + 30 + uFileNameLen; - DWORD uFileLen = m_storage.m_pFile->GetLength(); - DWORD uEndOffset = uFileLen - m_centralDir.GetBytesBefore(); - CZipActionCallback* pCallback = GetCallback(cbRename); - if (pCallback) - { - // do it right and sent the notification - pCallback->Init(fh.GetFileName(), GetArchivePath()); - pCallback->SetTotal(uEndOffset - uStartOffset); - } - bool bForward = iDelta > 0; - if (bForward) - m_storage.m_pFile->SetLength(uFileLen + iDelta); // ensure the seek is correct - - MovePackedFiles(uStartOffset, uEndOffset, abs(iDelta), pCallback, bForward); - if (pCallback) - pCallback->CallbackEnd(); - - if (!bForward) - m_storage.m_pFile->SetLength(uFileLen + iDelta); // delta < 0; shrink the file - - m_info.ReleaseBuf(); - - int iSize = GetCount(); - for (int i = uIndex + 1; i < iSize; i++) - m_centralDir[i]->m_uOffset += iDelta; - buf.Allocate(4+uNewFileNameLen); - WORD uExtraFieldSize = fh.GetExtraFieldSize(); - memcpy(buf, &uNewFileNameLen, 2); - memcpy(buf + 2, &uExtraFieldSize, 2); // to write everything at once - memcpy(buf + 4, fhNew.m_pszFileName, uNewFileNameLen); - pBuf = &buf; - iOffset = -4; - } - else - pBuf = &fhNew.m_pszFileName; - - m_storage.m_pFile->Seek(m_centralDir.GetBytesBefore() + fh.m_uOffset + 30 + iOffset, CZipAbstractFile::begin); - m_storage.m_pFile->Write(buf, buf.GetSize()); - m_centralDir.RenameFile(uIndex, szNewName); - if (m_bAutoFlush) - Flush(); - - return true; -} - -bool CZipArchive::UpdateReplaceIndex(int& iReplaceIndex, LPCTSTR lpszNewFileName) -{ - if (iReplaceIndex == -2) - iReplaceIndex = FindFile(lpszNewFileName); - if (iReplaceIndex < 0) - { - if (iReplaceIndex != -1) - iReplaceIndex = -1; - return true; - } - - if (GetSpanMode()!=0) - { - TRACE(_T("%s(%i) : You cannot replace files in a disk-spanning archive.\n"),__FILE__,__LINE__); - return false; - } - - if (!m_centralDir.IsValidIndex(iReplaceIndex)) - { - TRACE(_T("%s(%i) : Not valid replace index.\n"),__FILE__,__LINE__); - return false; - } - if (iReplaceIndex == GetCount() - 1) // replacing last file in the archive - { - RemoveLast(true); - iReplaceIndex = -1; - } - return true; -} - -void CZipArchive::MakeSpaceForReplace(int iReplaceIndex, DWORD uTotal, LPCTSTR lpszFileName) -{ - - ASSERT(iReplaceIndex < GetCount() - 1); - DWORD uReplaceStart = m_storage.m_pFile->GetPosition() - m_centralDir.GetBytesBefore(); - DWORD uReplaceEnd = m_centralDir.m_headers[iReplaceIndex + 1]->m_uOffset; - DWORD uReplaceTotal = uReplaceEnd - uReplaceStart; - int iDelta = uTotal - uReplaceTotal; - - if (iDelta != 0) - { - - // m_info.Init(); don't - the calling functions will - CZipActionCallback* pCallback = GetCallback(CZipArchive::cbReplace); - DWORD uFileLen = m_storage.m_pFile->GetLength(); - DWORD uUpperLimit = uFileLen - m_centralDir.GetBytesBefore(); // will be added in MovePackedFiles - if (pCallback) - { - pCallback->Init(lpszFileName, GetArchivePath()); - pCallback->SetTotal(uUpperLimit - uReplaceEnd); - } - - bool bForward = iDelta > 0; - if (bForward) - m_storage.m_pFile->SetLength(uFileLen + iDelta); // ensure the seek is correct - - MovePackedFiles(uReplaceEnd, uUpperLimit, abs(iDelta), pCallback, bForward); - - if (!bForward) - m_storage.m_pFile->SetLength(uFileLen + iDelta); // delta < 0; shrink the file - - m_storage.m_pFile->Seek(uReplaceStart, CZipAbstractFile::begin); - int iSize = m_centralDir.m_headers.GetSize(); - for (int i = iReplaceIndex + 1; i < iSize; i++) - m_centralDir.m_headers[i]->m_uOffset += iDelta; - if (pCallback) - pCallback->CallbackEnd(); - } -} - -void CZipArchive::MovePackedFiles(DWORD uStartOffset, DWORD uEndOffset, DWORD uMoveBy, CZipActionCallback* pCallback, bool bForward) -{ - ASSERT(m_info.m_pBuffer.GetSize() > 0); - uStartOffset += m_centralDir.GetBytesBefore(); - uEndOffset += m_centralDir.GetBytesBefore(); - - - DWORD uTotalToMove = uEndOffset - uStartOffset; - DWORD uPack = uTotalToMove > m_info.m_pBuffer.GetSize() ? m_info.m_pBuffer.GetSize() : uTotalToMove; - char* buf = (char*)m_info.m_pBuffer; - - - DWORD size_read; - bool bBreak = false; - do - { - - if (uEndOffset - uStartOffset < uPack) - { - uPack = uEndOffset - uStartOffset; - if (!uPack) - break; - bBreak = true; - - } - DWORD uPosition = bForward ? uEndOffset - uPack : uStartOffset; - - m_storage.m_pFile->Seek(uPosition, CZipAbstractFile::begin); - size_read = m_storage.m_pFile->Read(buf, uPack); - if (!size_read) - break; - - if (bForward) - uPosition += uMoveBy; - else - uPosition -= uMoveBy; - m_storage.m_pFile->Seek(uPosition, CZipAbstractFile::begin); - m_storage.m_pFile->Write(buf, size_read); - if (bForward) - uEndOffset -= size_read; - else - uStartOffset += size_read; - if (pCallback) - if (!(*pCallback)(size_read)) - ThrowError(CZipException::abortedAction); - } - while (!bBreak); - - if (uEndOffset != uStartOffset) - ThrowError(CZipException::internal); - -} diff --git a/harbour/contrib/hbziparch/ziparchive.h b/harbour/contrib/hbziparch/ziparchive.h deleted file mode 100644 index 6e7966886b..0000000000 --- a/harbour/contrib/hbziparch/ziparchive.h +++ /dev/null @@ -1,2050 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipArchive.h $ -// $Archive: /ZipArchive/ZipArchive.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -// -// Check the site http://www.artpol-software.com for the updated version of the library. -//////////////////////////////////////////////////////////////////////////////// -// -// The following information files are distributed along with this library: -// License.txt - licensing information -// gpl.txt - General Public License text -// Readme.txt - general information -// ChangeLog.txt - revision history -// faq.txt - frequently asked questions -// Appnote.txt - details on the zip format -// ( also available at ftp://ftp.pkware.com/appnote.zip) -// -// - - - -/** -* \file ZipArchive.h -* Interface for the CZipArchive class. -* -*/ - -#if !defined(AFX_ZIPARCHIVE_H__A7F528A6_1872_4071_BE66_D56CC2DDE0E6__INCLUDED_) -#define AFX_ZIPARCHIVE_H__A7F528A6_1872_4071_BE66_D56CC2DDE0E6__INCLUDED_ - -/** - \namespace ziparchv - A helper namespace. - \par Members - - CZipFileMapping - -*/ - - - - -/** - \struct CZipFileMapping ZipFileMapping.h - - Maps a file to the memory. A system-specific implementation. - Stored in ziparchv namespace. - - \c #include "ZipFileMapping.h" -*/ - - -// to ensure that the correct files are copied -// (see "Compatibility" chapter in the documentation). -// Rebuild the project after copying the files. -#ifdef ZIP_ARCHIVE_MFC_PROJ - #ifndef ZIP_ARCHIVE_MFC - #error You need to copy files from the MFC subdirectory\ - to the ZipArchive root directory and rebuild the project - #endif -#elif defined ZIP_ARCHIVE_STL_PROJ - #ifndef ZIP_ARCHIVE_STL - #error You need to copy files from the STL subdirectory\ - to the ZipArchive root directory and rebuild the project - #endif -#endif // - -#if (_MSC_VER > 1000) && (defined ZIP_HAS_DLL) - #pragma warning( disable : 4251 ) // needs to have dll-interface to be used by clients of class - #pragma warning( disable : 4275 ) // non dll-interface class used as base for dll-interface -#endif - - -//#ifdef __cplusplus -//extern "C" { -//#endif -#include "hbzlib.h" -//#ifdef __cplusplus -//} -//#endif - - -#include "zipexception.h" -#include "zipautobuffer.h" -#include "zipcentraldir.h" -#include "zipstorage.h" -#include "zippathcomponent.h" -#include "zipstring.h" -#include "ZipExport.h" - - -/** - Structure used as a parameter in CZipArchive::AddNewFile(CZipAddNewFileInfo& ); - Use one of constructors provided and then adjust the member variables that are - set to default values by #Defaults method. -*/ -struct ZIP_API CZipAddNewFileInfo -{ - CZipAddNewFileInfo(LPCTSTR lpszFilePath, bool bFullPath = true) - : m_szFilePath(lpszFilePath),m_bFullPath(bFullPath) - { - m_pFile = NULL; - Defaults(); - } - CZipAddNewFileInfo(LPCTSTR lpszFilePath, LPCTSTR lpszFileNameInZip) - : m_szFilePath(lpszFilePath), m_szFileNameInZip(lpszFileNameInZip) - { - m_pFile = NULL; - Defaults(); - } - CZipAddNewFileInfo(CZipAbstractFile* pFile, LPCTSTR lpszFileNameInZip) - : m_pFile(pFile), m_szFileNameInZip(lpszFileNameInZip) - { - Defaults(); - } - /** - the full path to the file to be added; if it is empty you need to set #m_pFile - */ - CZipString m_szFilePath; - - /** - the file name that will be stored in the archive (if the file is a directory, - there is a path separator automatically added at the end); #SetRootPath - function has no effect on this parameter - */ - CZipString m_szFileNameInZip; - - /** - It has only the meaning when #m_szFileNameInZip is not specified and #m_szFilePath is not empty. - - - if \c true, include full path of the file inside the archive (even if #m_szRootPath is set)
- - - if \c false only the filename without a path is stored in the archive
- - in this case if #m_szRootPath is set previously with #SetRootPath - and if the beginning of #m_szFilePath equals #m_szRootPath - then the filename is set to the remaining part of m_szFilePath - (you can say to m_lpszFilePath minus #m_szRootPath) - */ - bool m_bFullPath; - - /** - the compression level, see #OpenNewFile - */ - int m_iComprLevel; - - /** - the smartness level of of the library; can be one or more #Smartness - values (you can OR them);
- if zipsmCheckForEff is specified and due to it the file needs to be - reinserted into the archive without a compression and the callback - functor is specified, the callback functor's method Callback is called with the first argument set to - DWORD (-1) (you need to remember the last argument if you need the size of the file) - */ - int m_iSmartLevel; - - /** - the index of the existing file in the archive to be replaced by the file being added (the new file - goes into the same physical place as the old file - the archive may of course grow or shrink as a result) - -- >= 0 the index of the file to be replaced -- -1 do not replace any file and add the new file at the end of the archive (default) -- -2 if the new file has the same name as a file already in the archive then replace it or add at the end of the archive if it's filename is unique; it uses CZipArchive::FindFile with - the arguments \e iCaseSensitive and \e bFileNameOnly set to default values - - \note - - you replace files in disk-spanning archives (i.e. use a value different from -1) - - if the space size taken by the old file is different from the space size needed by the new file, the callback is called while moving data (see CZipArchive::cbReplace) - - this replaces the file physically, so no information from the file being replaced is retained (such as attributes, modification time, etc.) - - if you use an invalid index, the function will fail; if you specify the last file in the archive to be replaced, it'll be removed and the usual action taken - - the new file encryption does not depend on the old file encryption but only on the current password settings (see CZipArchive::SetPassword) - - if #m_iComprLevel is not 0 then a temporary archive is created in the temporary directory - (see CZipArchive::SetTempPath) or in the memory (if you use CZipArchive::zipsmMemoryFlag in #m_iSmartLevel) - - the most complicated scenario is when you try to replace the file and use CZipArchive::zipsmCheckForEff flag in #m_iSmartLevel and the file compression proves to be - inefficient (you can use the sample application \e ZipArc to observe the following process): - - first you get CZipArchive::cbAdd callback - the file is being compressed to a temporary archive, - - then the file compression proves to be inefficient and the file needs to be stored instead of compressed, - but first the space inside archive must be adjusted to fit the file being added in the place of file being replaced - you get CZipArchive::cbReplace, - - then, at the end, the file is being stored - you get CZipArchive::cbAddStore callback - - \see SetAdvanced - \see CZipArchive::WillBeDuplicated - */ - int m_iReplaceIndex; - - /** - the size of the buffer used while file operations - */ - unsigned long m_nBufSize; - - /** - instead of from a physical file, the data for compression is taken from the CZipAbstractFile object (e.g. from CZipMemFile) - - \note - - you have to leave #m_szFilePath empty if you set #m_pFile to not NULL - - the time of the file in zip is set to the current time, and the attributes to the default - file attributes (depending on the system) - - you cannot add directories this way - */ - CZipAbstractFile* m_pFile; - - /** - Set default values for #m_iSmartLevel, #m_iReplaceIndex, #m_nBufSize and #m_iComprLevel - */ - void Defaults(); -}; - - -/** - The representation of the zip archive file. - This class provides all the operations on the zip archive. - -*/ -class ZIP_API CZipArchive -{ - -public: - /** - The purpose of this structure is to hold the data that allow communication - with the zlib library - */ - struct ZIP_API CZipInternalInfo - { - - CZipInternalInfo() - { - m_iBufferSize = 65536; - } - virtual ~CZipInternalInfo(){} - - /** - Allocate internal buffer of m_iBufferSize size - */ - void Init() - { - m_pBuffer.Allocate(m_iBufferSize); - } - void ReleaseBuf() - { - m_pBuffer.Release(); - } - z_stream m_stream; ///< zlib library data stream - DWORD m_uUncomprLeft; ///< bytes left to uncompress - DWORD m_uComprLeft; ///< bytes left to decompress - DWORD m_uCrc32; ///< crc32 file control value - - /** - The size of the buffer used in decompressing data. - Set before opening the archive. - It is usually set with CZipArchive::SetAdvanced - (specify this value as the second argument). - \see CZipArchive::SetAdvanced - */ - DWORD m_iBufferSize; - - /** - This buffer caches data during compression and decompression. - */ - CZipAutoBuffer m_pBuffer; - }; - - CZipArchive(); - virtual ~CZipArchive(); - -/** - In non-UNICODE version just copy \e szSingle to \e szWide. - In UNICODE version works the same way as ZipPlatform::SingleToWide - \param szSingle - \param szWide - - \return (in non-UNICODE version the number of characters copied) - \see ZipPlatform::SingleToWide -*/ - static int SingleToWide(const CZipAutoBuffer &szSingle, CZipString& szWide); - -/** - In non-UNICODE version just copy \e lpWide to \e szSingle. - In UNICODE version works the same way as ZipPlatform::WideToSingle - \param lpWide - \param szSingle - \return (in non-UNICODE version the number of characters copied) - \see ZipPlatform::WideToSingle - -*/ - static int WideToSingle(LPCTSTR lpWide, CZipAutoBuffer &szSingle); - - -/** - Set the password for the file to be opened or created. - Use this method BEFORE opening or adding a file, but AFTER opening an archive - \param lpszPassword - set it to NULL to clear password - \return \c false if the password contains ASCII characters - with values 128 or higher or the file inside archive is opened - -*/ - bool SetPassword(LPCTSTR lpszPassword = NULL); - -/** - \return the current archive password or an empty string if there is no password -*/ - CZipString GetPassword()const ; - -/** - Set the buffer sizes. No buffer can be set smaller than 1024. - Use this method before opening the archive. The optimal size for - the write buffer in the disk spanning archive is the size of the volume. - - \param iWriteBuffer - the write cache size used - \see CZipStorage::m_iWriteBufferSize - \param iGeneralBuffer - buffer used in extracting, compressing, deleting, getting (#GetFromArchive) files, renaming and replacing - \see CZipInternalInfo::m_iBufferSize - \param iSearchBuffer - the buffer used in searching for the central dir - \see CZipCentralDir::m_iBufferSize - \see GetAdvanced -*/ - void SetAdvanced(int iWriteBuffer = 65536, int iGeneralBuffer = 65536, int iSearchBuffer = 32768); - - /** - retreive buffer size as set by #SetAdvanced - */ - void GetAdvanced(int* piWriteBuffer = NULL, int* piGeneralBuffer = NULL, int* piSearchBuffer= NULL) - { - if (piWriteBuffer) - *piWriteBuffer = m_storage.m_iWriteBufferSize; - if (piGeneralBuffer) - *piGeneralBuffer = m_info.m_iBufferSize; - if (piSearchBuffer) - *piSearchBuffer = m_centralDir.m_iBufferSize; - } - - /** - Enum values used as \e iWhich parameter in #SetCallback function. - You can assign several values to the same functor (OR them) - \see CZipActionCallback - */ - enum CallbackType - { - cbNothing = 0x0000, ///< you can use it for your own purposes - cbAdd = 0x0001, ///< called when adding a file with one of #AddNewFile functions - cbAddTmp = 0x0002, ///< called while adding a file (only on a disk-spanning archive) when the smartness level contains CZipArchive::zipsmCheckForEff or CZipArchive::zipsmCheckForEffInMem - ///< and if just compressed file is being moved from a temporary place (file or memory) to the archive - cbAddStore = 0x0004, ///< called while adding a file and if it's compressing has proven to be inefficient and it is now being stored (instead of compressed) in the archive; - ///< smartness level must contain CZipArchive::zipsmCheckForEff or CZipArchive::zipsmCheckForEffInMem; the archive can be disk-spanning or not - - cbExtract = 0x0008, ///< called when extracting a file with one of #ExtractFile functions - - cbDeleteCnt = 0x0010, ///< called before the actual deletion takes place and the map of holes and continuous areas is being created (it safe to break it by returning \c false from the callback method) - cbDelete = 0x0020, ///< called when moving data while deleting file(s) with function #DeleteFile or one of #DeleteFiles functions - - cbTest = 0x0040, ///< called when testing a file with #TestFile function - cbSave = 0x0080, ///< called when saving the central directory with CZipCentralDir::Write (usually on close or flush); it is safe to break on non-disk spanning archive - the saved part of - ///< the central directory will be removed from disk - cbGetFromArchive - = 0x0100, ///< called when using one of #GetFromArchive methods - cbRename = 0x0200, ///< called when during the renaming a file there is a need to make less or more space for the new filename - cbReplace = 0x0400, ///< called when moving data while replacing files to make less or more space for the new file - cbNextValue = 0x0800, ///< for CZipActionCallback overrides and user defined callbacks - - - cbSubActions= cbAddTmp | cbAddStore | cbDeleteCnt | cbReplace, ///< sub actions - they are part of bigger actions (#cbAddTmp | #cbAddStore | #cbDeleteCnt | #cbReplace) - cbActions = cbAdd | cbExtract | cbDelete | cbTest | cbSave | cbGetFromArchive | cbRename, ///< main actions (#cbAdd | #cbExtract | #cbDelete | #cbTest | #cbSave | #cbGetFromArchive | #cbRename) - cbAll = cbActions | cbSubActions ///< assign all callbacks to the same functor - }; - - - /** - - Set callback functors for the following operations on the zip archive: adding, extracting, testing or deleting files. - See \ref sectCallb information on how to use functors. - \param pCallback - the address of the functional object which class is derived from CZipActionCallback - (you need to override member function CZipCallback::Callback in the derived class) - Set it to \c NULL to clear callback for the selected actions. - \param iWhich - can be one or more (use logical OR) #CallbackType values. - - \see CZipActionCallback - \see GetCallback - - */ - void SetCallback(CZipActionCallback* pCallback = NULL, int iWhich = cbAll); - - /** - \return the callback \e iWhich set with #SetCallback - */ - CZipActionCallback* GetCallback(CallbackType iWhich) - { - return m_callbacks.Get(iWhich); - } - - /** - Set the callback functor used during operations on a - PKZIP compatible disk spanning archive to change disks. - Set it before opening the archive. If you open the archive - in the \ref PKSpan "PKZIP compatible mode" and don't set the callback functor, - the exception CZipException::noCallback will be thrown. - - Callback functor's method CZipSpanCallback::Callback is called when there is a need for a disk change. - Calling CZipArchive methods from inside this method may result in an unexpected behavior. - \param pCallback - the address of the functional object which class is derived from CZipSpanCallback - (you need to override member function CZipCallback::Callback in the derived class) - Set it to \c NULL to clear the callback. - - \see CZipSpanCallback - */ - void SetSpanCallback(CZipSpanCallback* pCallback = NULL){m_storage.m_pChangeDiskFunc = pCallback;} - - - - /** - Archive open modes used in #Open(LPCTSTR , int , int ) - and #Open(CZipMemFile, int ) - */ - enum OpenMode - { - zipOpen, ///< open an existing archive - /** - Open an existing archive as a read only file. - This mode is intended to use in a self extract code or opening - archive on storage without write access (e.g. CD-ROMS), - If you try to modify the archive in this mode, - an exception will be thrown. - */ - zipOpenReadOnly, - zipCreate, ///< create a new archive - zipCreateSpan ///< create a disk spanning archive - }; - - - -/** - Open or create a zip archive. - - The archive creation mode depends on \e iMode and \e iVolumesSize values: - - if \e iMode == #zipCreateSpan and \e iVolumeSize <= 0 then create disk spanning - archive in \ref PKSpan "PKZIP compatible mode" (pkzipSpan) - - if \e iMode == #zipCreateSpan and \e iVolumeSize > 0 then create disk spanning - archive in \ref TDSpan "TD compatible mode" (tdSpan) - - if \e iMode == #zipOpen and the existing archive is a spanned archive - then pkzipSpan mode is assumed if the archive is on a removable device - or tdSpan otherwise;
- if you want to open tdSpan archive on a removable device, set \e iVolumeSize - to a value different from 0 - - if \e iMode == #zipCreate then \e iVolumeSize doesn't matter - - \param szPathName - the path to the archive - \param iMode - one of the #OpenMode values - \param iVolumeSize - the volume size in the disk spanning archive; - the size of the volume may be from 1 to INT_MAX , - and the bigger - the faster is creation and extraction (no file changes between volumes) - but the size of the whole archive is the same. - If you're creating disk-spanning archive in \ref TDSpan "TD span compatible mode" - and plan later to convert it to \ref PKSpan "PKZIP compatible mode" (see \ref sectSpan), it is good to set this this value to - about the size of the diskette (a little less just in case). - - \note Throws exceptions. - \see Open(CZipMemFile&, int); - \see GetSpanMode -*/ - void Open(LPCTSTR szPathName, int iMode = zipOpen, int iVolumeSize = 0); - - -/** - Open or create the archive in memory. The CZipMemFile object is not closed - after closing the archive, so that is it possible to work with it afterwards. - \param mf - CZipMemFile structure to create archive in or extract from - \note This is important: you shouldn't destroy CZipMemFile object before - closing the archive, because you'll get an error; - \param iMode - Open mode. - The following modes are valid: #zipOpen, #zipOpenReadOnly, #zipCreate - \note Throws exceptions. - \see Open(LPCTSTR, int, int); -*/ - void Open(CZipMemFile& mf, int iMode = zipOpen); - -/** - Set #m_szRootPath to a specified value. Use it if you don't want to set - \e bFullPath argument in #AddNewFile or #ExtractFile to true and you - don't want to strip the whole path neither, but only a specific beginning. - Use it AFTER opening the archive and before using #AddNewFile or #ExtractFile. - See \ref q9 "the FAQ" for the example of use. - \param szPath - Set it to the string that you want to be omitted from the beginning of the path of the file - in the archive
- if \c NULL - clears the #m_szRootPath and no path beginning will be matched against it - - \note Set the case-sensitivity with #SetCaseSensitivity - - \see AddNewFile - \see ExtractFile - \see GetRootPath - -*/ - void SetRootPath(LPCTSTR szPath = NULL); - - - /** - Return the current value of #m_szRootPath - \return CZipString - */ - CZipString GetRootPath()const - { - return m_szRootPath; - } - - /** - The levels of smartness of the adding files action (see #AddNewFile) - \note If you wish to use \e zipsmCheckForEff, you should use - \e zipsmNotCompSmall as well, because it will save you the time - ( the small file will be surely larger after compression, so that - we can add it not compressed straight away);the compression level - is always ignored for a directory and set to 0 - */ - - enum Smartness - { - zipsmLazy = 0x0000, ///< do not bother (you know what you're doing after all) - zipsmCPassDir = 0x0001, ///< clear password for directories - zipsmCPFile0 = 0x0002, ///< clear password for files of 0 size - zipsmNotCompSmall = 0x0004, ///< do not compress files smaller than 5 bytes (they are always stored larger than uncompressed) - zipsmCheckForEff = 0x0008, ///< check whether the compressed file is larger than uncompressed and if so, remove it and store without the compression; - ///< in the disk spanning mode, the temporary file is used for that: if the file compression is efficient, the data is not compressed - ///< again, but moved from the temporary file to the archive; you can use #SetTempPath() to set the path where the - ///< file will be created or you can let the library figure it out (the library tries first the system default temporary directory, - ///< if it is not present or there is not enough space there, it tries the current directory, if it fails, no temporary file is created - ///< and the compression goes the usual way - - zipsmMemoryFlag = 0x0010, ///< combine it with zipsmCheckForEff or use zipsmCheckForEffInMem, you can also use this when replacing files see note at CZipAddNewFileInfo::m_iReplaceIndex - - zipsmCheckForEffInMem = zipsmMemoryFlag | zipsmCheckForEff, ///< the same as #zipsmCheckForEff, but the temporary file is created created in memory instead (the temporary directory set with #SetTempPath() is ignored); has the meaning only with a disk-spanning archive, - ///< non-disk spanning archives don't need a temporary file - zipsmSmartPass = zipsmCPassDir | zipsmCPFile0, ///< smart password policy (a combination of \e zipsmCPassDir and \e zipsmCPFile0) - zipsmSmartAdd = zipsmNotCompSmall | zipsmCheckForEff, ///< smart adding (a combination of \e zipsmNotCompSmall and \e zipsmCheckForEff) - zipsmSafeSmart = zipsmSmartPass | zipsmNotCompSmall, ///< safe smart (smartest without checking for efficiency) - zipsmSmartest = zipsmSmartPass | zipsmSmartAdd, ///< smart at its best - - - zipsmInternal01 = 0xf000 ///< for internal use only - - }; - - - /** - Add a new file to the archive. You can set the callback functor with #SetCallback. - \param info see CZipAddNewFileInfo - \return \c if it returns false then the file was not added, but the internal - state allows you to add other files (which is not possible after throwing - an exception) - - \note - - If you abort while adding a file in a non-disk-spanning archive, the added data will be removed from the archive - - Throws exceptions. - - \see SetCallback - \see AddNewFile(LPCTSTR, LPCTSTR, int, int, unsigned long) - \see AddNewFile(LPCTSTR, int, bool, int, unsigned long) - \see AddNewFile(CZipMemFile&, LPCTSTR, int, int, unsigned long) - */ - bool AddNewFile(CZipAddNewFileInfo& info); - bool AddNewFileDrv(CZipAddNewFileInfo& info); - - - /** - \see AddNewFile(CZipAddNewFileInfo& ); the parameters are equivalent to CZipAddNewFileInfo member variables - - */ - bool AddNewFile(LPCTSTR lpszFilePath, int iComprLevel = -1, bool bFullPath = true, - int iSmartLevel = zipsmSafeSmart, unsigned long nBufSize = 65536); - - bool AddNewFileDrv(LPCTSTR lpszFilePath, int iComprLevel = -1, bool bFullPath = true, - int iSmartLevel = zipsmSafeSmart, unsigned long nBufSize = 65536); - /** - \see AddNewFile(CZipAddNewFileInfo& ); the parameters are equivalent to CZipAddNewFileInfo member variables - */ - bool AddNewFile(LPCTSTR lpszFilePath, - LPCTSTR lpszFileNameInZip, - int iComprLevel = -1, - int iSmartLevel = zipsmSafeSmart, - unsigned long nBufSize = 65536); - - /** - \see AddNewFile(CZipAddNewFileInfo& ); the parameters are equivalent to CZipAddNewFileInfo member variables - */ - bool AddNewFile(CZipMemFile& mf, - LPCTSTR lpszFileNameInZip, - int iComprLevel = -1, - int iSmartLevel = zipsmSafeSmart, - unsigned long nBufSize = 65536); - - - -/** - Add a new file to the opened zip archive. The zip archive cannot be - an existing disk spanning archive (existing at the moment of opening archive), - because modifying such an archive is not possible (at least not with this - version ). - - \param header - The structure that provides additional information about the added file. - The following fields are valid: - - \e m_uMethod - file compression method; can be 0 (storing) or Z_DEFLATE (deflating) - otherwise Z_DEFLATE is assumed - - \e m_uModDate, \e m_uModTime - Use CZipFileHeader::SetTime to set them. - If \e lpszFilePath is not NULL this fields are overwritten and updated automatically. - See CZipFileHeader::SetTime - - \e m_uExternalAttr - Attributes of the file. - If \e lpszFilePath is not NULL this field is overwritten and updated automatically. - Use #SetFileHeaderAttr to set them. See #SetFileHeaderAttr. - - \e m_szFileName - A filename (may be with path) to be stored inside archive - to represent this file. See CZipFileHeader::SetFileName - - \e m_szComment - A file comment. See CZipFileHeader::SetComment - - \e m_pExtraField - LOCAL extra field, use #SetExtraField after opening - a new file, but before closing it to set the not local extra field - in the header in the central directory. See #SetExtraField
- Other fields are ignored - they are updated automatically. - If the function returns \c true, \link #GetSystemCompatibility - system compatibility \endlink for this object is - set to the correct value (the same as #m_iArchiveSystCompatib), - additionally if \e lpszFilePath was not NULL, the attributes and - the time fields are filled with information retrieved from - the file pointed by \e lpszFilePath. - \param iLevel - The level of compression (-1, 0 - 9). - The are several preset values for the compression level: - - Z_DEFAULT_COMPRESSION : -1 (equals 6) - - Z_NO_COMPRESSION : 0 - - Z_BEST_SPEED : 1 - - Z_BEST_COMPRESSION : 9 - \param lpszFilePath - The path to the file to retrieve date stamp and attributes from. - These values are stored inside the archive. - \param uInternal - for internal use only - - \return \c false in the following cases: - - the \e lpszFilePath is not NULL and the file attributes and data was not correctly retrieved - - a file is already opened for extraction or compression - - archive is an existing disk span archive - - maximum file count inside archive already reached (65536) - \note Throws exceptions. - -*/ - bool OpenNewFile(CZipFileHeader & header, int iLevel = Z_DEFAULT_COMPRESSION, LPCTSTR lpszFilePath = NULL, DWORD uInternal = 0); - -/** - Compress the contents of the buffer and write it to a new file. - \param pBuf - the buffer containing the data to be compressed and written - \param iSize - the number of bytes to be written from the buffer - \return \c false if the new file hasn't been opened yet - \note Throws exceptions. - \see OpenNewFile -*/ - bool WriteNewFile(const void *pBuf, DWORD iSize); - - -/** - Set the extra field in the central directory of the currently opened file. - Must be used after opening a new file in the archive, but before closing it - To set the local extra field, set it in the CZipFileHeader structure passed - as the argument to the #OpenNewFile - \param pBuf - the bufer with the data to be copied - \param iSize - the size of the extra field in the buffer - \see OpenNewFile -*/ - void SetExtraField(const char *pBuf, WORD iSize); - -/** - Close the new file in the archive. - \return \c false if there is no new file opened - \param bAfterException - it will close the new file without writing anything (call it also - with this parameter set to \c true after an exception other than CZipException::abortedSafely was - thrown from one of #AddNewFile functions) - \note Throws exceptions. - \see OpenNewFile -*/ - bool CloseNewFile(bool bAfterException = false); - -/** - Acquire a file with the given index from another archive. - The compressed data of the file from another archive are copied - without decompressing to the current archive. - You can set the callback functor with #SetCallback. - \param zip - an opened archive to get the file from (must not be multi-disk) - \param uIndex - a zero-based index of the file to get from the \e zip archive - \param iReplaceIndex the same as CZipAddNewFileInfo::m_iReplaceIndex - \param bKeepSystComp - if \c false, which is default, then the file from \e zip archive - system compatibility is converted to the current archive system - compatibility (if they differ) - \return \c false if the operation could not be performed (either of archives is closed, - a file inside either of archives is opened, \e zip archive is multi-disk or the current - archive is an existing multi-disk archive) - \note Throws exceptions
- (when an exception is thrown, you may need to call #CloseNewFile with \e bAfterException set to \c true, to make the archive reusable). - \note it is safe to abort the action (by returning false from the callback call) in non-disk spanning archive and when no replacing is taking place - (the file not entirely added is removed from the archive) - \see SetCallback - \see GetFromArchive(CZipArchive& , CZipWordArray &, bool) - \see GetFromArchive(CZipArchive& , CZipStringArray &, bool) - \see FindMatches - \see SetAdvanced -*/ - bool GetFromArchive(CZipArchive& zip, WORD uIndex, int iReplaceIndex = -1, bool bKeepSystComp = false) - { - - m_info.Init(); - bool bRet; - try - { - bRet = GetFromArchive(zip, uIndex, iReplaceIndex, bKeepSystComp, GetCallback(cbGetFromArchive)); - } - catch(...) - { - m_info.ReleaseBuf(); - throw; - } - m_info.ReleaseBuf(); - if (bRet && m_bAutoFlush) - Flush(); - - return bRet; - } - - /** - Acquire files with the given indexes from another archive. - - \param aIndexes - an array of zero-based indexes of the files inside the \e zip archive - - \see GetFromArchive(CZipArchive& , WORD, int, bool) - - \note - - To get files which filenames match a specified pattern, use #FindMatches function - */ - bool GetFromArchive(CZipArchive& zip, CZipWordArray &aIndexes, bool bKeepSystComp = false); - - /** - Acquire files with the given indexes from another archive. - \param aNames - an array of filenames inside the \e zip archive; - - \see GetFromArchive(CZipArchive& , WORD, int, bool) - \see EnableFindFast - - \note - - Set the case-sensitivity with #SetCaseSensitivity - - Enables FindFast if not enabled - - */ - - bool GetFromArchive(CZipArchive& zip, CZipStringArray &aNames, bool bKeepSystComp = false) - { - CZipWordArray indexes; - zip.GetIndexes(aNames, indexes); - return GetFromArchive(zip, indexes, bKeepSystComp); - - } - - /** - Get indexes of the files stored int \e aNames array and put them into \e aIndexes - \param aNames - an array of filenames inside the archive; - \param aIndexes - an array of indexes to be build - \note - - Set the case-sensitivity with #SetCaseSensitivity - - Enables FindFast if not enabled - - */ - void GetIndexes(const CZipStringArray &aNames, CZipWordArray& aIndexes); - -/** - Extract the file from the archive. You can set the callback functor with #SetCallback. - The argument \e lpszNewName may point to the full path and is influenced by \e bFullPath - argument (if \e lpszNewName contains drive specification then it is removed) - \param uIndex - the index of the file to extract - \param lpszPath - \verbatim - The PATH only to extract the file to. May not be NULL. If you wish to - use UNC path you need to replace \\\\ at the beginning of UNC path with \\\\?\UNC\ . - \endverbatim - \param bFullPath
- - if \c true, then extract with the full path - in this case the resulting - file path is \e lpszPath plus the path stored in the archive or plus \e lpszNewName - if \e lpszNewName is not NULL.
- - if \c false, the destination file path is \e lpszPath + \e the filename only - extracted from the path stored in the archive or from \e lpszNewName if - \e lpszNewName is specified;
- if #m_szRootPath is set previously with #SetRootPath then to \e lpszPath - is added the path stored in the archive (or \e lpszNewName if - \e lpszNewName is specified) that has removed the beginning that equals - #m_szRootPath (if there is no common beginning then is behaves like - #m_szRootPath was empty) - \param lpszNewName - The new name of the file after extraction. - If NULL the original filename stored in the archive is used. - May point to the full path but, if \e bFullPath is \c false, only the filename is extracted from this argument, - \param nBufSize - the size of the buffer used while file operations - \return \c true if successful - \note - - To extract files which filenames match a specified pattern, use #FindMatches function - - Throws exceptions. - \see SetCallback - \see ExtractFile(WORD, CZipMemFile&, DWORD) - \see FindMatches -*/ - bool ExtractFile(WORD uIndex, LPCTSTR lpszPath, bool bFullPath = true, - LPCTSTR lpszNewName = NULL, DWORD nBufSize = 65536); - - - /** - The same as #ExtractFile(WORD , LPCTSTR , bool , LPCTSTR , DWORD ) - but instead to a physical file, this function decompress the data into CZipMemFile object - \note - - if you pass CZipMemFile object already with data, its contents are NOT overwirtten, but the decompressed data is appended at the end - - if you try to extract a directory, the function will return \c false - */ - bool ExtractFile(WORD uIndex, CZipMemFile& mf, DWORD nBufSize = 65536); - -/** - Open the file with the given index in the archive for extracting. - Not successful opening the file doesn't lock the whole archive, so - you can try to open another one (after catching an exception if it was - thrown). Throw exception CZipException::badPassword if the password - was not set for the encrypted file. - \param uIndex - the index of the file - \return \c true if successful - \note Throws exceptions. -*/ - bool OpenFile(WORD uIndex); - -/** - Decompress currently opened file to the buffer. - \param pBuf - buffer to receive data - \param iSize - the size of the buffer - \return the number of bytes read - \see OpenFile - \note Throws exceptions. -*/ - DWORD ReadFile(void *pBuf, DWORD iSize); - - -/** - Test the file with the given index for the integrity. You can set the callback functor with #SetCallback. - The method throws exceptions but performs all the necessary cleanup - before, so that the next file can be tested after catching the exception. - \param uIndex - index of the file to test - \param uBufSize - the size of the buffer used during extraction - \return \c false if the incorrect action has been taken by - the user or the programmer (it is when #OpenFile or #GetFileInfo returned \c false or \e uBufSize is 0). - If the file didn't passed the test or there was a disk I/O error or the password supplied was incorrect, an exception is thrown. - \note Throws exceptions. - \see SetCallback - -*/ - bool TestFile(WORD uIndex, DWORD uBufSize = 65536); - -/** - Perform the necessary cleanup after an exception was thrown - while testing the archive so that next files in the archive can be tested. - Called by #TestFile. Does not remove the file headers - information from the central directory. - \see TestFile - \see CZipCentralDir::Clear -*/ - void CloseFileAfterTestFailed(); - -/** - Get the local extra filed of the currently opened - for extraction file in the archive. - \param pBuf - the buffer to receive the data - \param iSize - the size of the buffer - \return If \e pBuf is NULL or iSize is 0, returns the size of the local extra field. - Returns -1 if there is no file opened for the extraction. -*/ - int GetLocalExtraField(char* pBuf, int iSize)const ; - -/** - The same as CZipArchive::CloseFile(LPCTSTR), but additionally - closes \e file. - \param file - OPENED CZipFile structure of the extracted file - \return - \note Throws exceptions. - \see CZipArchive::CloseFile(LPCTSTR) -*/ - int CloseFile(CZipFile &file); - - -/** - Close the file opened for extraction in the archive and copy its date and - attributes to the file pointed by \e lpszFilePath - \param lpszFilePath - Points to the path of the file to have the date and attributes information updated. - \param bAfterException - Set to \c true to close the file inside archive after an exception has been - thrown, to allow futher operations on the archive. - \warning Close the file pointed by \e lpszFilePath before using this method, - because the system may not be able to retrieve information from it. - \return
- - "1" = ok - - "-1" = some bytes left to uncompress - probably due to a bad password or corrupted archive - - "-2" = setting extracted file date and attributes was not successful - \note Throws exceptions. -*/ - int CloseFile(LPCTSTR lpszFilePath = NULL, bool bAfterException = false); - -/** - Delete the file from the archive with the given index. - You can set the callback functor with #SetCallback. - If you plan to delete more than one file, use one of DeleteFiles functions rather than calling DeleteFile - successively, because these functions are optimized for deleting multiple files - \param uIndex - a zero-based index - \note Throws exceptions. - \see SetCallback - \see DeleteFiles(CZipWordArray&) - \see DeleteFiles(const CZipStringArray&) - \see FindMatches -*/ - void DeleteFile(WORD uIndex); - -/** - Delete files from the archive. - You can set the callback functor with #SetCallback. - Sorts \e aIndexes array in an ascending order. - \param aIndexes - an array of zero-based indexes of the files inside the archive - \note - - To remove files which filenames match a specified pattern, use #FindMatches function - - Throws exceptions. - \see SetCallback - \see DeleteFile - \see DeleteFiles(const CZipStringArray& ) - \see FindMatches -*/ - void DeleteFiles(CZipWordArray &aIndexes); - - -/** - Delete files from the archive. - You can set the callback functor with #SetCallback. - \param aNames - an array of filenames inside the archive; - \note - - Set the case-sensitivity with #SetCaseSensitivity - - Enables FindFast if not enabled - - Throws exceptions. - \see SetCallback - \see DeleteFile - \see DeleteFiles(CZipWordArray&) - \see EnableFindFast -*/ - void DeleteFiles(const CZipStringArray &aNames); - - -/** - Set the global comment in the archive. - \param lpszComment - the file comment - \return \c false if the archive is closed or if it is an existing disk spanning archive - \note Throws exceptions. -*/ - bool SetGlobalComment(LPCTSTR lpszComment); - - -/** - \return the global comment or an empty string if the archive is closed -*/ - CZipString GetGlobalComment()const ; - - -/** - Set the comment of the file with the given index inside the archive. - \param uIndex - zero-based index of the file in the archive - \param lpszComment - a comment to add - \return \c false if the comment change is impossible - \note Throws exceptions. -*/ - bool SetFileComment(WORD uIndex, LPCTSTR lpszComment); - -/** - \return the path of the currently opened archive volume -*/ - CZipString GetArchivePath()const; - -/** - \return
- - a one-based number of the current disk - - 0 if there is no current disk (the archive is closed) - \note Useful mostly while working with the disk-spanning archive in creation to find out - how many disks were already created. To find out how many disks are in an existing disk-spanning archive, - use the function #GetCentralDirInfo -*/ - int GetCurrentDisk()const ; - -/** - Return the disk spanning mode of the current archive. - - \return
- - -2 - existing TD mode compatible disk spanning archive - - -1 - existing PKZIP compatible - - 0 - no disk spanning - - 1 - PKZIP compatible in creation - - 2 - TD compatible in creation - - \see \ref PKSpan, \ref TDSpan - -*/ - int GetSpanMode()const - { - return m_storage.m_iSpanMode * m_storage.IsSpanMode(); - } - - /** - case-sensitivity values used as argument \e iCaseSensitive in #FindFile - */ - enum FFCaseSens - { - ffDefault, ///< use the default case-sensitivity as set with #SetCaseSensitivity function; - ///< if CZipCentralDir::m_findarray was build before with a different case-sensitivity, - ///< it is rebuild again, if it hasn't been build so far, it is build now with the - ///< default case-sensitivity - ffCaseSens, ///< perform a case-sensitive search (if the \c CZipArchive is non-case-sensitive, - ///< a less effective search is perfomed); does not rebuild CZipCentralDir::m_findarray, - ///< but if the array hasn't been built yet, it is build now as \b non-case-sensitive - ///< (you can use \c SetCaseSensitivity(true) and then #ffDefault to build it as case-sensitive) - ffNoCaseSens ///< perform a non-case-sensitive search (if the \c CZipArchive is case-sensitive, - ///< a less effective search is performed); does not rebuild CZipCentralDir::m_findarray, - ///< but if the array hasn't been built yet, it is build now as \b case-sensitive - ///< (you can use \c SetCaseSensitivity(false) and then #ffDefault to build it as non-case-sensitive) - - }; - -/** - Find the file in the archive. - If the archive wasn't opened with CZipCentralDir::m_bConvertAfterOpen set to \c true, - this function automatically convert all the filenames with the function - CZipCentralDir::ConvertAll and set CZipCentralDir::m_bConvertAfterOpen to \c true. - This function requires \link CZipCentralDir::m_bFindFastEnabled FindFast \endlink - feature enabled. - \param lpszFileName - the name of the file to be found in the archive; must be with path unless - you set \e bFileNameOnly to \c true. Use path separators the same as they are for your system - (\e "\" for Windows and \e "/" for Unix/Linux) - \param iCaseSensitive can be one of #FFCaseSens values - \param bFileNameOnly - if \c true, the function tries to find a filename without a path (a less effective search is performed); if you wish to find - a directory name, do not end it with the path separator, which is required if you set \e bFileName to \c false - \return
- - the index of the file found - - -1 if there is no such a file in the archive - \see CZipCentralDir::FindFileNameIndex - \see EnableFindFast - \see CZipCentralDir::ConvertAll - \see SetConvertAfterOpen -*/ - int FindFile(LPCTSTR lpszFileName, int iCaseSensitive = ffDefault, bool bFileNameOnly = false); - -/** - Get the info of the file with the given index. - \param fhInfo - the structure to receive info - \param uIndex - a zero-based index of the file inside the archive - \return \c true if successful -*/ - bool GetFileInfo(CZipFileHeader & fhInfo, WORD uIndex) const; - - -/** - \param bOnlyFiles - if \c true, the directories are not inluded in a total count; - default is \c false - \return the number of files in the archive -*/ - int GetCount(bool bOnlyFiles = false)const - { - int iTotalCount = m_centralDir.m_headers.GetSize(); - if (bOnlyFiles) - { - int iCount = 0; - for (int i = 0; i < iTotalCount; i++) - if (!m_centralDir.m_headers[i]->IsDirectory()) - iCount++; - return iCount; - } - else - return iTotalCount; - } - - /** - values used in #Close function as parameter \e iAfterException - */ - enum CloseAfterException - { - afNoException, ///< normal close, no exception was thrown before by CZipArchive object - afAfterException, ///< an exception has been thrown, don't write any data but perform necessary cleaning to reuse CZipArchive object for another archive - afWriteDir ///< the same as above, but write the central directory end structure to the archive, so that we can save at least the files that have - ///< been added properly and maybe try to repair the archive later - }; - -/** - Close the archive. - \param iAfterException - one of #CloseAfterException enum values - \param bUpdateTimeStamp - if \c true, set the modification date of the zip file to the date of the newest file in the archive; - in disk-spanning mode only the last archive file will have the time stamp updated; - you can use this option even without performing any additional processing on the archive, just open and close it - \note Throws exceptions if \e iAfterException is different from \c afAfterException -*/ - void Close(int iAfterException = afNoException, bool bUpdateTimeStamp = false); - - -/** - Test if the archive is closed (a whole or the current volume only) - \param bArchive
- - \c true: test for the whole archive - - \c false: test for the volume file only - - \return \c true if closed -*/ - bool IsClosed(bool bArchive = true)const ; - - /** - Write the central directory to the archive and flushes the internal buffers to the disk, - so that the archive is finalized on the disk, but you can still modify it. Use it after - opening (or creating) and modifying the archive if you want to prevent the loss - of the data you've compressed so far in case of the program crash.
- If you use it on a disk spanning archive in creation it will not be closed, but its state - will be changed from "archive in creation" to "an existing span archive". Use it when you finish adding files to the disk-spanning archive and want to - begin extracting or testing it. It follows that you can call it only once in this case. However, if - after finalizing the disk spanning archive it turns out that it is one disk only, it is converted to - a normal archive and you can use it as such. If you want to know what is the state of the archive after using - this function call #GetSpanMode. - \note - - Cannot be used on existing disk spanning archives (they are not modifable anyway) - - If you have an archive with a huge central directory, it'll influence the perfomance calling this function without a reason. - - Throws exceptions. - \see GetSpanMode - \see SetAutoFlush - \see GetAutoFlush - - */ - void Flush(); - - - /** - Set the CZipArchive object to call #Flush after each operation that modifies the archive - (adding a new file, deleting file(s), modifying the global or a file comment). - It is useful when we want to prevent the loss of data in case of the program crash - the zip file will be then finalized on the disk. - Use it after opening the archive. - \note - - You can set AutoFlush only for non-disk spanning archives, however you can call #Flush once for a disk-spanning archive in creation. - - If you have an archive with a huge central directory, setting Auto-Flush will influence the performance. - \see Flush - \see GetAutoFlush - */ - void SetAutoFlush(bool bAutoFlush = true); - - - /** - return the current #m_bAutoFlush value - \see Flush - \see SetAutoFlush - */ - bool GetAutoFlush()const {return m_bAutoFlush;} - -/** - Return the system compatibility of the current archive. - System compatibility value for the single file in the archive - (represented by CZipFileHeader) influences file attributes conversion - (the file attributes are defined differently across the platforms). - When opening an existing archive CZipArchive assumes the system compatibility - of the whole archive to be the same as of the first file in the archive - (if present). In other cases the current system value is assumed which is - taken from ZipPlatform::GetSystemID during creating or opening an archive - \remark - If the existing archive during opening is empty, ZipPlatform::GetSystemID - is assumed to be the default system for the files that will be added to the archive. - - \return - one of the enum values defined in \link ZipCompatibility::ZipPlatforms - ZipCompatibility.h \endlink - \see ZipCompatibility::ZipPlatforms - \see ZipPlatform::GetSystemID - \see CZipFileHeader::GetSystemCompatibility -*/ - int GetSystemCompatibility() const {return m_iArchiveSystCompatib;} - -/** - Set the system compatibility of the archive. By default it is set to the - current system value (the one returned by ZipPlatform::GetSystemID() function). - Use it after opening the archive, but before adding a new file or using - SetFileHeaderAttr() function - \param iSystemComp - can be one of ZipCompatibility::ZipPlatforms values - \return - return \c false if the value \e iSystemComp is not supported - (ZipCompatibility::IsPlatformSupported returns \c false for the value) - or it is not possible to set it right now -*/ - bool SetSystemCompatibility(int iSystemComp); - -/** - Set the attributes for CZipFileHeader structure to be used - in #OpenNewFile method as an argument. - This special procedure is taken, because the system compatibility must - be set for CZipFileHeader prior to the value, which must be identical to - the return value of #GetSystemCompatibility method. - \param header - the structure to have attributes set - \param uAttr - attributes to set - \note Throws exceptions if the archive system or the current system - is not supported by the ZipArchive library. - \see GetSystemCompatibility -*/ - void SetFileHeaderAttr(CZipFileHeader& header, DWORD uAttr); - - -/** - A helper for a various purposes (needed e.g. by the program that - cracks the zip archives password) - \return the pointer to the static CRC table in the zlib library - -*/ - static const DWORD* GetCRCTable() - { - return get_crc_table(); - } - -/** - Return the underlying archive storage medium. - \warning A method for a very advanced use - you normally never need it. - \return the pointer to #m_storage - \see CZipStorage -*/ - CZipStorage* GetStorage(){return &m_storage;} - - -/** - Set #m_bDetectZlibMemoryLeaks value. - \param bDetect - \note Use before opening a file in the archive. - \see m_bDetectZlibMemoryLeaks - -*/ -/* - void SetDetectZlibMemoryLeaks(bool bDetect) - { - if (m_iFileOpened != nothing) - { - TRACE(_T("CZipArchive::SetDetectZlibMemoryLeaks: Set it before opening a file in the archive"),__FILE__,__LINE__); - return; - } - m_bDetectZlibMemoryLeaks = bDetect; - - } -*/ -/** - Set CZipCentralDir::m_bConvertAfterOpen value. - The default value is \c true. - Setting this value to \c false is generally not effective and is intended - only for quick and short operations on archives with lots of files inside - (e.g. open archive, make an operation on a file which index you already know - and close the archive - using #FindFile function already makes setting this - value to \c false inefficient) - - \param bConvertAfterOpen - \note Use before opening the archive. - \see CZipCentralDir::m_bConvertAfterOpen -*/ - void SetConvertAfterOpen (bool bConvertAfterOpen) - { - if (!IsClosed()) - { - TRACE(_T("CZipArchive::SetConvertAfterOpen: Set it before opening the archive"),__FILE__,__LINE__); - return; - } - m_centralDir.m_bConvertAfterOpen = bConvertAfterOpen; - - } - -/** - Enable fast finding by the file name of the files inside the archive. - Set CZipCentralDir::m_bFindFastEnabled to \c true, which is required by #FindFile. - #FindFileIt is called by #FindFileif necessary. It builds CZipCentralDir::m_findarray - with the default case-sensitivity (set with #SetCaseSensitivity) - \note Call it only after opening the archive. - \param bEnable - \see CZipCentralDir::m_bFindFastEnabled - \see FindFile -*/ - void EnableFindFast(bool bEnable = true); - - - /** - After you enable FindFast feature with #EnableFindFast, you can retrieve - how the files are sorted in CZipCentralDir::m_findarray (you can use it - in your own program if you need to display the sorted list and do not want - to duplicate data) - - \param iFindFastIndex - index in CZipCentralDir::m_findarray (not necessary the same as the one you'd - pass to #GetFileInfo); the number of items in this array is the same - as the number of files in the archive (you can retrieve it with - #GetCount) - - \return - index of the file in central directory (now you can call #GetFileInfo to get - the information); if the value is \c -1 then you have not called - #EnableFindFast before or the archive is closed or the \e iFindFastIndex - is out of range) - */ - int GetFindFastIndex(int iFindFastIndex) const - { - if (IsClosed()) - { - TRACE(_T("CZipArchive::GetFindFastIndex: ZipArchive not yet opened.\n"),__FILE__,__LINE__); - return -1; - } - - return m_centralDir.GetFindFastIndex(iFindFastIndex); - } - - - /** - Set a temporary path used when compressing files and #zipsmCheckForEff - is specified as an argument in #AddNewFile and the disk spanning archive - is in creation. - \param lpszPath set it to NULL to clear the temporary path and let the - library figure it out (it uses the system temporary directory if possible) - \param bForce if \e lpszPath is not \c NULL and this parameter set to \c true - the directory is created if it doesn't exists (if the given directory - does not exists , the temporary file will not be created) - \see AddNewFile - \see Smartness - \see GetTempPath - */ - void SetTempPath(LPCTSTR lpszPath = NULL, bool bForce = true); - - - - /** - enum values used in #PredictFileNameInZip - */ - enum Predict - { - - prDir, ///< if an argument is a directory, add a separator at the end - prFile, ///< treat the argument as a common file - prAuto ///< treat the argument as a directory only if it has a path separator at the end - - }; - - /** - Given the file path in the form it would be passed to #AddNewFile - as \e lpszFilePath argument, the function returns the file name - as it would be stored in the archive.
- The function takes into account the root path set with #SetRootPath. You can use this function - to eliminate duplicates before adding a list of files.
- - \param lpszFilePath - the file path as it would be passed to #AddNewFile function - \param bFullPath - the same as \e bFullPath in #AddNewFile - \param iWhat - one of #Predict values to treat \e lpszFilePath correctly - \param bExactly - if \c true, return the filename exactly as it would look inside the archive i.e. convert slash to backslash, and perform ANSI->OEM conversion; - otherwise return the filename with the path separators that are used by default in the system - - \return a modified file path - */ - CZipString PredictFileNameInZip(LPCTSTR lpszFilePath, bool bFullPath, int iWhat = prAuto, bool bExactly = false)const ; - - /** - Check if the filename will be duplicted in the archive, if added to the archive in the given form - \param bFileNameOnly - if \c true, assume that the filename is duplicated if only the filename (no path) is the same (\e bFullPath is ignored), otherwise the whole filename with path is taken into account. - - \b Default: \c false - - The rest of the parameters have the same meaning as in #PredictFileNameInZip. - - \return the zero-based index of the file in the archive that the filename would be duplicated, or -1, if the filename is unique - */ - int WillBeDuplicated(LPCTSTR lpszFilePath, bool bFullPath, bool bFileNameOnly = false, int iWhat = prAuto); - - - /** - Predict the full filename with path after extraction. The parameters (except for the first) are in the form you'd pass - to the #ExtractFile(WORD , LPCTSTR , bool , LPCTSTR , DWORD ) function. The function takes into account the root path set with #SetRootPath. - \param lpszFileNameInZip - the filename of the file inside the archive (may be \c NULL if lpszNewName is not \c NULL) - \param lpszPath - \param bFullPath - \param lpszNewName - \return a predicted file path - */ - CZipString PredictExtractedFileName(LPCTSTR lpszFileNameInZip, LPCTSTR lpszPath, bool bFullPath, LPCTSTR lpszNewName = NULL)const ; - - /** - - Return the current value of #m_szTempPath - - \return CZipString - */ - CZipString GetTempPath()const - { - return m_szTempPath; - } - -/** - Function used in conjunction with #m_szRootPath to trim paths in #AddNewFile and #ExtractFile - \param zpc - \see SetRootPath - -*/ - CZipString TrimRootPath(CZipPathComponent& zpc)const ; - - /** - Remove \e lpszBeginning from the beginning of the \e szPath. Both argument are - considered to be paths so they matches up to the path separator. - - \param lpszBeginning - \param szPath - \param pCompareFunction (see: #m_pZipCompare) - - - \return \c true if the path beginning was removed - */ - static bool RemovePathBeginning(LPCTSTR lpszBeginning, CZipString& szPath, ZIPSTRINGCOMPARE pCompareFunction); - - /** - Set the default archive case-sensitivity. Affects the following functions: - - #FindFile - - #FindMatches - - #EnableFindFast - - #TrimRootPath - - #DeleteFiles - - - - \param bCaseSensitive - the default CZipArchive case-sensitivity depends on the system and is set - as follows: - - on Windows: \c false
- - on Linux: \c true - \note Set it before using one of the functions above or leave it as it is by default; - - */ - - void SetCaseSensitivity(bool bCaseSensitive) - { - m_bCaseSensitive = bCaseSensitive; - m_pZipCompare = GetCZipStrCompFunc(bCaseSensitive); - } - - /** - Return the central directory information. - \see GetCentralDirSize - */ - void GetCentralDirInfo(CZipCentralDir::Info& info)const; - - - /** - Get the central directory size. - \see CZipCentralDir::GetSize - \see GetCentralDirInfo - */ - DWORD GetCentralDirSize(bool bWhole = true) const - { - return m_centralDir.GetSize(bWhole); - } - - /** - return \c true if the archive cannot be modified, because it is an existing disk spanning archive - or it was opened with #zipOpenReadOnly - */ - bool IsReadOnly(){return m_storage.IsReadOnly();} - - - /** - - If you set \e bIgnore to \c true, CRC is not checked for the files being tested or extracted. - This method is useful when working with Java TM Archives (jar). - The CRC is checked by default. You can use this function on an opened or closed archive. - - */ - void SetIgnoreCRC(bool bIgnore = true){m_bIgnoreCRC = bIgnore;} - - /** - A class used in wildcard pattern matching. - This class is based on code by J. Kercheval, created 01/05/1991 - and available as a public domain at http://www.snippets.org. - */ - class ZIP_API CWildcard - { - public: - - - enum Match - { - matchNone, ///< for internal use - matchValid, ///< valid match - matchEnd, ///< premature end of pattern string - matchAbort, ///< premature end of text string - matchRange, ///< match failure on [..] construct - matchLiteral, ///< match failure on literal match - matchPattern ///< bad pattern - }; - - enum Pattern - { - patternEmpty = -4, ///< [..] construct is empty - patternClose, ///< no end bracket in [..] construct - patternRange, ///< malformed range in [..] construct - patternEsc, ///< literal escape at end of pattern - patternValid, ///< valid pattern - }; - - - /** - Match the pattern against the string \e lpszText - A match means the entire string \e lpszText is used up in matching. - - \param lpszText - the string to match against - \param iRetCode - if not \c NULL, set to one of #Match values indicating the return code - \return \c true if \e lpszText matches the pattern. - \see SetPattern - */ - bool IsMatch(LPCTSTR lpszText, int* iRetCode = NULL); - - /** - - \param lpszPattern - - \return \c true if \e lpszPattern has any special wildcard characters. - - */ - static bool IsPattern(LPCTSTR lpszPattern); - - /** - Test the pattern for validity. - - \param lpszPattern - the pattern to test - \param iErrorType - if not \c NULL, set to one of #Pattern values indicating the return code - \return \c true if \e lpszPattern is a well formed regular expression according - to the CWildcard class syntax (see #SetPattern) - */ - static bool IsPatternValid(LPCTSTR lpszPattern, int* iErrorType = NULL); - - /** - Match the pattern \e lpszPattern against the string \e lpszText - A match means the entire string \e lpszText is used up in matching. - - - \param lpszPattern - see #SetPattern - \param lpszText - the string to match against - \return - one of #Match values - */ - static int Match(LPCTSTR lpszPattern, LPCTSTR lpszText); - - CWildcard(){} - /** - Initialize the pattern. - \see SetPattern - */ - CWildcard(LPCTSTR lpszPattern, bool bCaseSensitive) - { - SetPattern(lpszPattern, bCaseSensitive); - } - virtual ~CWildcard(){} - - /** - Set the pattern to \e lpszPattern. - \param lpszPattern - - In the pattern string: - - * matches any sequence of characters(zero or more) - - ? matches any character - - [SET] matches any character in the specified set, - - [!SET] or[^SET] matches any character not in the specified set. - - A set is composed of characters or ranges; a range looks like - character hyphen character(as in 0 - 9 or A - Z).[0 - 9a - zA - Z_] is the - minimal set of characters allowed in the[..] pattern construct. - Other characters are allowed(ie. 8 bit characters) if your system - will support them. - - \note To suppress the special syntactic significance of any of []*?!^-\, - and match the character exactly, precede it with a \ - */ - void SetPattern(LPCTSTR lpszPattern, bool bCaseSensitive) - { - m_szPattern = lpszPattern; - m_bCaseSensitive=bCaseSensitive; - if (!bCaseSensitive) - m_szPattern.MakeLower(); - } - operator LPCTSTR() - { - return (LPCTSTR)m_szPattern; - } - protected: - bool m_bCaseSensitive; - static int MatchAfterStar(LPCTSTR p , LPCTSTR t); - CZipString m_szPattern; - }; - - - /** - This function finds the indexes of the files, which filenames match the specified pattern and stores - these indexes in the array. The indexes can be used then e.g. in deleting (CZipArchive::DeleteFiles) or - extracting files (CZipArchive::ExtractFile). - - \param lpszPattern - the pattern to match (see CWildcard::SetPattern on how to build the pattern). The case-sensitivity of the pattern - is set to the global archive case-sensitivity (set with #SetCaseSensitivity) - \param ar - the array which will contain the indexes of the files which filenames match the pattern; the contents of the array are NOT clearead, but the - indexes are appended to it - \param bFullPath
- - if \c true, match the filename with path (if present) of the file (if the file is a directory, end it with the path separator or use a pattern that will recognize it) - - otherwise match only the name of the file (if the file is a directory, do not end it with the path separator) - - */ - void FindMatches(LPCTSTR lpszPattern, CZipWordArray& ar, bool bFullPath = true)const; - - - /** - Change the name of the file with the given index. - - \param uIndex - zero-based index of the file - \param lpszNewName - new name for the file - \return - - \note Throws exceptions. - \see SetAdvanced - */ - bool RenameFile(WORD uIndex, LPCTSTR lpszNewName); - - /** - - If \c true, the drive letter is removed from the filename stored inside the archive when adding a new file to the archive. It affects - #AddNewFile, #ExtractFile, #PredictFileNameInZip, #PredictExtractedFileName, #WillBeDuplicated methods. - - \b Default: \c true - */ - bool m_bRemoveDriveLetter; - -protected: - - /** - \param iReplaceIndex index of file to be replaced - \param uTotal the size of the new file to replace existing - \param lpszFileName the filename for callback initialization - */ - void MakeSpaceForReplace(int iReplaceIndex, DWORD uTotal, LPCTSTR lpszFileName); - /** - A structure for the internal use only. Clears the password if necessary and - restores it later (also in case of an exception). - */ - struct ZIP_API CZipSmClrPass - { - void ClearPasswordSmartly(CZipArchive* pZip) - { - m_pZip = pZip; - m_szPass = pZip->GetPassword(); - if (!m_szPass.IsEmpty()) - pZip->SetPassword(); - } - ~CZipSmClrPass() - { - if (!m_szPass.IsEmpty()) - m_pZip->SetPassword(m_szPass); - } - CZipString m_szPass; - CZipArchive* m_pZip; - }; - - /** - Holds map of holes and areas to remain when deleting files from the archive. - A structure for the internal use only. - */ - struct ZIP_API CZipDeleteInfo - { - CZipDeleteInfo(){m_pHeader = NULL; m_bDelete = false;} - CZipDeleteInfo(CZipFileHeader* pHeader, bool bDelete) - :m_pHeader(pHeader), m_bDelete (bDelete){} - CZipFileHeader* m_pHeader; - bool m_bDelete; - }; - - - /** - Storage for callback functors. A structure for the internal use only. - \see SetCallback - */ - struct ZIP_API CZipClbckStrg : public CZipMap - { - void Set(CZipActionCallback* pCallback, CallbackType iType) - { - if (pCallback) - { - SetAt(iType, pCallback); - } - else - RemoveKey(iType); - } - CZipActionCallback* Get(CallbackType iType) - { - CZipActionCallback* pCallback = NULL; - if (Lookup(iType, pCallback)) - { - pCallback->m_iType = iType; - return pCallback; - } - else - return NULL; - } - - }; - - - /** - \see CZipClbckStrg - */ - CZipClbckStrg m_callbacks; - - - /** - Write central directory calling a callback functor if available - */ - void WriteCentralDirectory(bool bFlush = true); - - /** - Default archive case-sensitivity - \see SetCaseSensitivity - */ - bool m_bCaseSensitive; - - /** - a pointer to the function in CZipString structure, - used to compare elements; can point to Compare, CompareNoCase, - Collate or CollateNoCase function address in CZipString structure ZIPSTRINGCOMPARE is defined as follows:
- typedef int (CZipString::*ZIPSTRINGCOMPARE)( LPCTSTR ) const; - */ - ZIPSTRINGCOMPARE m_pZipCompare; - - /** - Internal data. - \see CZipInternalInfo - */ - CZipInternalInfo m_info; - - - /** - Physical layer of the archive. - \see CZipStorage - */ - CZipStorage m_storage; - - /** - A central directory object. - \see CZipCentralDir - */ - CZipCentralDir m_centralDir; - - /** - The open mode of the current file inside archive. - */ - enum OpenFileType - { - extract = -1, ///< current file opened for extraction - nothing, ///< no file inside archive opened - compress ///< a new file opened for compression - }; - - /** - Takes one of the #OpenFileType enum values. - */ - char m_iFileOpened; - - /** - The current AutoFlush value. - \see Flush - \see SetAutoFlush - \see GetAutoFlush - */ - bool m_bAutoFlush; - - /** - The value set with #SetIgnoreCRC - */ - bool m_bIgnoreCRC; - - - -/** - The root path to be omitted in #AddNewFile and #ExtractFile functions - from the beginning of the full file path. Set by #SetRootPath - \see TrimRootPath - \see SetRootPath -*/ - CZipString m_szRootPath; - - /** - A temporary path set with #SetTempPath function - \see SetTempPath - \see AddNewFile - \see Smartness - */ - CZipString m_szTempPath; - -/** - Open the archive in the given mode. - Called by #Open(LPCTSTR, int, int) and #Open(CZipMemFile&, int). - \param iMode - an opening mode - \note Throws exceptions. -*/ - void OpenInternal(int iMode); - - /** - The system code of the current archive. All new files in the archive - will be created regarding this value. Can be one of the enum values - defined in \link ZipCompatibility::ZipPlatforms ZipCompatibility.h - \endlink - - \see GetSystemCompatibility - */ - int m_iArchiveSystCompatib; - -/** - Free the memory allocated by the zlib library that hasn't been freed - due to an error in the zlib library (usually never happens). -*/ - void EmptyPtrList(); - - - -/** - Move the range of data in the archive specified by the \e uStartOffset - and \e uEndOffset by \e uToMove - -*/ - void MovePackedFiles(DWORD uStartOffset, DWORD uEndOffset, DWORD uMoveBy, CZipActionCallback* pCallback, bool bForward = false); - - /** - Remove recently added file (used by AddNewFile) if compressed is larger than uncompressed or if callback method return \c false. - \param bRemoveAnyway if \c true, do not check for the efficiency, but remove the file - - */ - bool RemoveLast(bool bRemoveAnyway = false); - - /** - It is used in GetFromArchive public functions and in AddNewFile and the callback parameter is needed - */ - bool GetFromArchive(CZipArchive& zip, WORD uIndex, int iReplaceIndex, bool bKeepSystComp, CZipActionCallback* pCallback); - - /** - \return whether the code should continue or not - */ - bool UpdateReplaceIndex(int& iReplaceIndex, LPCTSTR lpszNewFileName); - -/** - \return the currently opened for compression or decompression - file inside the archive NULL if there is no file opened -*/ - CZipFileHeader* CurrentFile(); - -/** - If the parameter \e iErr signalizes a zlib library error, throw CZipException - \param iErr - a zlib library error to check - \note Throws exceptions. -*/ - void CheckForError(int iErr); - - -/** - Throw a CZipException error. - \param err - the error code - \see CZipException::ZipErrors - \param bZlib - if \c true, treat \e err as a zlib error code and perform the conversion to the one of CZipException codes. - \see CZipException::Throw -*/ - void ThrowError(int err, bool bZlib = false); - - - typedef CZipPtrList::iterator CZipPtrListIter; - CZipPtrList m_list; ///< a list holding pointers to the memory areas allocated by the zlib library - - - static void* _zliballoc(void* opaque, UINT items, UINT size); ///< memory allocator called by the zlib library - static void _zlibfree(void* opaque, void* address); ///< memory deallocator called by the zlib library - - - /** - Specify whether to control memory allocation and freeing by the zlib library. - - \b Default: \c true - \note Set it before opening a file (new or existing) in the archive. - \see SetDetectZlibMemoryLeaks - - */ -// bool m_bDetectZlibMemoryLeaks; - - - /** - Copyright string. - */ - static const TCHAR m_gszCopyright[]; - -/** - \defgroup Cryptography Cryptography - Methods performing data encryption and decryption - and attributes used by them. -*/ - /*@{*/ - -/** - Decode \e uCount bytes from the internal buffer. - \see m_info - \see CZipInternalInfo::m_pBuffer - -*/ - void CryptDecodeBuffer(DWORD uCount); -/** - Encode the internal buffer. - \see m_info - \see CZipInternalInfo::m_pBuffer -*/ - void CryptEncodeBuffer(); - -/** - Encode the character \e c and update \link #m_keys encryption keys \endlink. - -*/ - void CryptEncode(char &c); -/** - Create an encryption header for the new file in the archive. - \param iCrc - A control value. Use the two lower bytes of CZipFileHeader::m_uModTime. - This entails the need for a data description presence at the end of - the compressed data. We cannot use the real CRC now, because we don't know - it yet. - \param buf - a buffer to receive the header - \see CryptCheck -*/ - void CryptCryptHeader(long iCrc, CZipAutoBuffer& buf); -/** - \internal - \return -*/ - DWORD CryptCRC32(DWORD l, char c); -/** - Decode the character \e c and update \link #m_keys encryption keys \endlink. -*/ - void CryptDecode(char &c); - /** - \internal - */ - char CryptDecryptByte(); - -/** - Decrypt the encryption header and check its control value. - The control value depends on the presence of the data descriptor. - \return \c true if the control value is correct - \see CryptCryptHeader -*/ - bool CryptCheck(); -/** - Update \link #m_keys encryption keys \endlink with the given value. -*/ - void CryptUpdateKeys(char c); -/** - Initialize \link #m_keys encryption keys \endlink. -*/ - void CryptInitKeys(); - /** - The archive password. If empty, the new file will not be encrypted. - */ - CZipAutoBuffer m_pszPassword; - - /** - Encryption keys. - The key values are initialized using a supplied encryption password. - \see CryptInitKeys - */ - DWORD m_keys[3]; - - /*@}*/ -}; - - - -#endif // !defined(AFX_ZIPARCHIVE_H__A7F528A6_1872_4071_BE66_D56CC2DDE0E6__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipautobuffer.cpp b/harbour/contrib/hbziparch/zipautobuffer.cpp deleted file mode 100644 index bf15a477b7..0000000000 --- a/harbour/contrib/hbziparch/zipautobuffer.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipAutoBuffer.cpp $ -// $Archive: /ZipArchive_STL/ZipAutoBuffer.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" -#include "zipautobuffer.h" -#include - -// #ifdef _DEBUG -// #undef THIS_FILE -// static char THIS_FILE[]=__FILE__; -// #define new DEBUG_NEW -// #endif - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CZipAutoBuffer::CZipAutoBuffer() -{ - m_iSize = 0; - m_pBuffer = NULL; -} - -CZipAutoBuffer::CZipAutoBuffer(DWORD iSize, bool bZeroMemory) -{ - m_iSize = 0; - m_pBuffer = NULL; - Allocate(iSize, bZeroMemory); -} - -CZipAutoBuffer::~CZipAutoBuffer() -{ - Release(); -} - - -void CZipAutoBuffer::Release() -{ - if (m_pBuffer) - { - delete [] m_pBuffer; - m_iSize = 0; - m_pBuffer = NULL; - } -} - -char* CZipAutoBuffer::Allocate(DWORD iSize, bool bZeroMemory) -{ - if (iSize != m_iSize) - Release(); - else - { - if (bZeroMemory) - memset(m_pBuffer, 0, iSize); // zerowanie bufora - return m_pBuffer; - } - - if (iSize > 0) - { - m_pBuffer = new char [iSize]; - if (bZeroMemory) - memset(m_pBuffer, 0, iSize); // zerowanie bufora - m_iSize = iSize; - } - else - m_pBuffer = NULL; - - return m_pBuffer; -} - - -CZipAutoBuffer::CZipAutoBuffer(const CZipAutoBuffer& buffer) -{ - m_pBuffer = NULL; - m_iSize = 0; - - if (buffer.m_pBuffer) - { - Allocate(buffer.m_iSize); - memcpy(m_pBuffer, buffer.m_pBuffer, buffer.m_iSize); - } -} -CZipAutoBuffer& CZipAutoBuffer::operator=(const CZipAutoBuffer& buffer) -{ - if (this == &buffer) - return *this; - Release(); - if (buffer.m_pBuffer) - { - Allocate(buffer.m_iSize); - memcpy(m_pBuffer, buffer.m_pBuffer, buffer.m_iSize); - } - return *this; -} diff --git a/harbour/contrib/hbziparch/zipautobuffer.h b/harbour/contrib/hbziparch/zipautobuffer.h deleted file mode 100644 index 7eaaf46e51..0000000000 --- a/harbour/contrib/hbziparch/zipautobuffer.h +++ /dev/null @@ -1,78 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipAutoBuffer.h $ -// $Archive: /ZipArchive/ZipAutoBuffer.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipAutoBuffer.h -* Interface for the CZipAutoBuffer class. -* -*/ - -#if !defined(AFX_ZIPAUTOBUFFER_H__DEC28C20_83FE_11D3_B7C3_EDEC47A8A86C__INCLUDED_) -#define AFX_ZIPAUTOBUFFER_H__DEC28C20_83FE_11D3_B7C3_EDEC47A8A86C__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "ZipExport.h" -/** - A smart buffer freeing its contents on destruction. -*/ -class ZIP_API CZipAutoBuffer -{ -public: - operator char*() - { - return m_pBuffer; - } -#ifndef __BORLANDC__ - operator const char*() const // Borland seems to have problems with this - { - return m_pBuffer; - } -#endif - - - - - - // may produce ambiguity on some compilers -// operator const char*() const -// { -// return m_pBuffer; -// } - const char* GetBuffer() const {return m_pBuffer;} - char* Allocate(DWORD iSize, bool bZeroMemory = false); - void Release(); - DWORD GetSize() const - { - return m_iSize; - } - bool IsAllocated() const - { - return (m_pBuffer != NULL); - } - CZipAutoBuffer(DWORD iSize, bool bZeroMemory = false); - CZipAutoBuffer(); - CZipAutoBuffer(const CZipAutoBuffer& buffer); - virtual ~CZipAutoBuffer(); - CZipAutoBuffer& operator=(const CZipAutoBuffer& buffer); -protected: - char* m_pBuffer; - DWORD m_iSize; -}; - -#endif // !defined(AFX_ZIPAUTOBUFFER_H__DEC28C20_83FE_11D3_B7C3_EDEC47A8A86C__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipbaseexception.h b/harbour/contrib/hbziparch/zipbaseexception.h deleted file mode 100644 index 6eb4b00719..0000000000 --- a/harbour/contrib/hbziparch/zipbaseexception.h +++ /dev/null @@ -1,22 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipBaseException.h $ -// $Archive: /ZipArchive_STL/ZipBaseException.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ZIPBASEEXCEPTION_H__ -#define __ZIPBASEEXCEPTION_H__ - -typedef std::exception CZipBaseException; - -#endif //__ZIPBASEEXCEPTION_H__ diff --git a/harbour/contrib/hbziparch/zipcentraldir.cpp b/harbour/contrib/hbziparch/zipcentraldir.cpp deleted file mode 100644 index 7b792f2b41..0000000000 --- a/harbour/contrib/hbziparch/zipcentraldir.cpp +++ /dev/null @@ -1,852 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipCentralDir.cpp $ -// $Archive: /ZipArchive/ZipCentralDir.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" -#include "zipcentraldir.h" -#include "ziparchive.h" -#include "zipfilemapping.h" -#include "zipplatform.h" - - -#define CENTRALDIRSIZE 22 - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -char CZipCentralDir::m_gszSignature[] = {0x50, 0x4b, 0x05, 0x06}; -CZipCentralDir::CZipCentralDir() -{ - m_bConvertAfterOpen = true; - m_bFindFastEnabled = false; - m_bCaseSensitive = false; - m_pCompare = GetCZipStrCompFunc(ZipPlatform::GetSystemCaseSensitivity()); - m_pStorage = NULL; - m_pOpenedFile = NULL; - m_iBufferSize = 32768; - -} - -void CZipCentralDir::Init() -{ - m_info.m_bOnDisk = false; - m_info.m_uBytesBeforeZip = m_info.m_uCentrDirPos = 0; - m_pOpenedFile = NULL; - m_pszComment.Release(); - -} - -CZipCentralDir::~CZipCentralDir() -{ - Clear(); -} - -void CZipCentralDir::Read() -{ - ASSERT(m_pStorage); - WORD uCommentSize; - m_info.m_uCentrDirPos = Locate(); - m_pStorage->m_pFile->Seek(m_info.m_uCentrDirPos, CZipAbstractFile::begin); - CZipAutoBuffer buf(CENTRALDIRSIZE); - - int uRead = m_pStorage->m_pFile->Read(buf, CENTRALDIRSIZE); - if (uRead != CENTRALDIRSIZE) - ThrowError(CZipException::badZipFile); - memcpy(&m_szSignature, buf, 4); - memcpy(&m_info.m_uThisDisk, buf + 4, 2); - memcpy(&m_info.m_uDiskWithCD, buf + 6, 2); - memcpy(&m_info.m_uDiskEntriesNo,buf + 8, 2); - memcpy(&m_info.m_uEntriesNumber,buf + 10, 2); - memcpy(&m_info.m_uSize, buf + 12, 4); - memcpy(&m_info.m_uOffset, buf + 16, 4); - memcpy(&uCommentSize, buf + 20, 2); - buf.Release(); - - - m_pStorage->UpdateSpanMode(m_info.m_uThisDisk); - // if m_uThisDisk is not zero, it is enough to say that it is a multi disk archive - ASSERT((!m_info.m_uThisDisk && (m_info.m_uEntriesNumber == m_info.m_uDiskEntriesNo) && !m_info.m_uDiskWithCD) || m_info.m_uThisDisk); - - - - if (!m_pStorage->IsSpanMode() && !m_info.CheckIfOK_1()) - ThrowError(CZipException::badZipFile); - - if (uCommentSize) - { - m_pszComment.Allocate(uCommentSize); - uRead = m_pStorage->m_pFile->Read(m_pszComment, uCommentSize); - if (uRead != uCommentSize) - ThrowError(CZipException::badZipFile); - } - - m_info.SetBytesBeforeZip(m_pStorage->IsSpanMode() != 0); - - if (!m_info.CheckIfOK_2()) - ThrowError(CZipException::badZipFile); - - m_info.m_bOnDisk = true; - m_pStorage->ChangeDisk(m_info.m_uDiskWithCD); - - if (!m_info.m_uSize) - return; - - ReadHeaders(); -} - -DWORD CZipCentralDir::Locate() -{ - - // maximum size of end of central dir record - long uMaxRecordSize = 0xffff + CENTRALDIRSIZE; - DWORD uFileSize = m_pStorage->m_pFile->GetLength(); - - if ((DWORD)uMaxRecordSize > uFileSize) - uMaxRecordSize = uFileSize; - - CZipAutoBuffer buf(m_iBufferSize); - - long uPosInFile = 0; - int uRead = 0; - // backward reading - while (uPosInFile < uMaxRecordSize) - { - uPosInFile = uRead + m_iBufferSize; - if (uPosInFile > uMaxRecordSize) - uPosInFile = uMaxRecordSize; - - int iToRead = uPosInFile - uRead; - - m_pStorage->m_pFile->Seek(-uPosInFile, CZipAbstractFile::end); - int iActuallyRead = m_pStorage->m_pFile->Read(buf, iToRead); - if (iActuallyRead != iToRead) - ThrowError(CZipException::badZipFile); - // search from the very last bytes to prevent an error if inside archive - // there are packed other arhives - for (int i = iToRead - 4; i >=0 ; i--) - if (!memcmp((char*)buf + i, m_gszSignature, 4)) - return uFileSize - (uPosInFile - i); - - uRead += iToRead - 3; - - } - - ThrowError(CZipException::cdirNotFound); - return 0; -} - -void CZipCentralDir::ThrowError(int err) const -{ - CZipException::Throw(err, m_pStorage->m_pFile->GetFilePath()); -} - - -void CZipCentralDir::ReadHeaders() -{ - m_pStorage->m_pFile->Seek(m_info.m_uOffset + m_info.m_uBytesBeforeZip, CZipAbstractFile::begin); - RemoveHeaders(); //just in case - for (int i = 0; i < m_info.m_uEntriesNumber; i++) - { - CZipFileHeader* pHeader = new CZipFileHeader; - m_headers.Add(pHeader); - - if (!pHeader->Read(m_pStorage)) - ThrowError(CZipException::badZipFile); - ConvertFileName(true, true, pHeader); - } - SortHeaders(); // this is necessary when deleting files and removing data descriptors - if (m_bFindFastEnabled) - BuildFindFastArray(m_bCaseSensitive); -} - -void CZipCentralDir::SortHeaders() -{ - // we cannot use the Sort method of the CZipWordArray, - // because we store pointers (and we need to store pointers - // to make sure that the address of the CZipFileHeader structure - // remains the same while working with the library) - int iSize = m_headers.GetSize(); - if (iSize) - qsort((void*)&(m_headers[0]),iSize , sizeof(CZipFileHeader*), CompareHeaders); -} - -void CZipCentralDir::Clear(bool bEverything) -{ - m_pOpenedFile = NULL; - m_pLocalExtraField.Release(); - if (bEverything) - { - RemoveHeaders(); - m_findarray.RemoveAll(); - m_pszComment.Release(); - } -} - - -bool CZipCentralDir::IsValidIndex(int uIndex)const -{ - return uIndex < m_headers.GetSize() && uIndex >= 0; -} - - -void CZipCentralDir::OpenFile(WORD uIndex) -{ - WORD uLocalExtraFieldSize; - m_pOpenedFile = (*this)[uIndex]; - m_pStorage->ChangeDisk(m_pOpenedFile->m_uDiskStart); - m_pStorage->m_pFile->Seek(m_pOpenedFile->m_uOffset + m_info.m_uBytesBeforeZip, CZipAbstractFile::begin); - if (!m_pOpenedFile->ReadLocal(m_pStorage, uLocalExtraFieldSize)) - ThrowError(CZipException::badZipFile); - - - m_pLocalExtraField.Release(); // just in case - if (uLocalExtraFieldSize) - { - int iCurrDsk = m_pStorage->GetCurrentDisk(); - m_pLocalExtraField.Allocate(uLocalExtraFieldSize); - m_pStorage->Read(m_pLocalExtraField, uLocalExtraFieldSize, true); - if (m_pStorage->GetCurrentDisk() != iCurrDsk) - ThrowError(CZipException::badZipFile); - } -} - -void CZipCentralDir::CloseFile(bool bAfterException) -{ - if (!m_pOpenedFile) - return; - m_pLocalExtraField.Release(); - if (!bAfterException && m_pOpenedFile->IsDataDescr()) - { - CZipAutoBuffer buf(12); - m_pStorage->Read(buf, 4, false); - // in span mode, files that are divided between disks have bit 3 of flag set - // which tell about the presence of the data descriptor after the compressed data - // This signature may be in the disk spanning archive that is one volume only - // (it is detected as a non disk spanning archive) - if (memcmp(buf, CZipStorage::m_gszExtHeaderSignat, 4) != 0) // there is no signature - m_pStorage->m_pFile->Seek(-4, CZipAbstractFile::current); - - - m_pStorage->Read(buf, 12, false); - if (!m_pOpenedFile->CheckCrcAndSizes(buf)) - ThrowError(CZipException::badZipFile); - } - m_pOpenedFile = NULL; -} - -// add new header using the argument as a template -CZipFileHeader* CZipCentralDir::AddNewFile(const CZipFileHeader & header, int iReplaceIndex) -{ - CZipFileHeader* pHeader = new CZipFileHeader(header); - m_pOpenedFile = pHeader; - WORD uIndex; - DWORD uOffset = 0; - bool bReplace = IsValidIndex(iReplaceIndex); - if (bReplace) - { - CZipFileHeader* pfh = m_headers[iReplaceIndex]; - uOffset = pfh->m_uOffset + m_info.m_uBytesBeforeZip; - RemoveFile(pfh, iReplaceIndex, false); - m_headers.InsertAt(iReplaceIndex, pHeader); - uIndex = (WORD)iReplaceIndex; - } - else - uIndex = m_headers.Add(pHeader); - - if (m_bFindFastEnabled) - InsertFindFastElement(pHeader, uIndex); // GetCount > 0, 'cos we've just added a header - RemoveFromDisk(); - if (bReplace) - m_pStorage->m_pFile->Seek(uOffset, CZipAbstractFile::begin); - else - m_pStorage->m_pFile->SeekToEnd(); - return pHeader; -} - - -void CZipCentralDir::RemoveFromDisk() -{ - if (m_info.m_bOnDisk) - { - ASSERT(!m_pStorage->IsSpanMode()); // you can't add files to the existing disk span archive or to delete them from it - m_pStorage->m_pFile->SetLength(m_info.m_uBytesBeforeZip + m_info.m_uOffset); - m_info.m_bOnDisk = false; - } - else - m_pStorage->Flush(); // if remove from disk is requested, then the archive modification will follow, so flush the buffers -} - - -void CZipCentralDir::CloseNewFile() -{ - CZipAutoBuffer buf(ZIPARCHIVE_DATADESCRIPTOR_LEN + 4); - short iToWrite = 0; - bool bIsSpan = m_pStorage->IsSpanMode() != 0; - bool bEncrypted = m_pOpenedFile->IsEncrypted(); - if (m_pOpenedFile->IsDataDescr()) - { - if (bIsSpan || bEncrypted) - { - memcpy(buf, m_pStorage->m_gszExtHeaderSignat, 4); - iToWrite += 4; - } - } - else /*if (!IsSpan)*/ - { - ASSERT(!bIsSpan && !bEncrypted); - m_pStorage->Flush(); - // the offset contains bytes before zip (set while writting the local header) - m_pStorage->m_pFile->Seek(m_pOpenedFile->m_uOffset + 14, CZipAbstractFile::begin); - // we don't have to restore the pointer, because before adding a new file, - // the pointer is moved to the end - } - - m_pOpenedFile->GetCrcAndSizes(buf + iToWrite); - iToWrite += ZIPARCHIVE_DATADESCRIPTOR_LEN; - - // offset set during writing the local header - m_pOpenedFile->m_uOffset -= m_info.m_uBytesBeforeZip; - - // write the data descriptor and a disk spanning signature at once - m_pStorage->Write(buf, iToWrite, true); - if (!bIsSpan) - { - if (bEncrypted) - { - // write the information to the local header too - m_pStorage->Flush(); - m_pStorage->m_pFile->Seek(m_info.m_uBytesBeforeZip + m_pOpenedFile->m_uOffset + 14, CZipAbstractFile::begin); - m_pStorage->Write(buf + 4, ZIPARCHIVE_DATADESCRIPTOR_LEN, true); - } - m_pStorage->Flush(); - } - - m_pOpenedFile = NULL; - -} - -void CZipCentralDir::Write(CZipActionCallback* pCallback) -{ - if (m_info.m_bOnDisk) - return; - if (!m_pStorage->IsSpanMode()) - { - m_pStorage->Flush(); - m_pStorage->m_pFile->SeekToEnd(); - } - -// else -// // we are at the end already - - m_info.m_uEntriesNumber = (WORD)m_headers.GetSize(); - m_info.m_uSize = 0; - bool bDontAllowDiskChange = false; - // if there is a disk spanning archive in creation and it is only one-volume, - // (current disk is 0 so far, no bytes has been written so we know they are - // all in the buffer) make sure that it will be after writing central dir - // and make it a non disk spanning archive - if (m_pStorage->IsSpanMode() && m_pStorage->GetCurrentDisk() == 0) - { - DWORD uVolumeFree = m_pStorage->VolumeLeft(); - // calculate the size of data descriptors already in the buffer or on the disk - // (they will be removed in the non disk spanning archive): - // multi span signature at the beginnig (4 bytes) + the size of the data - // descr. for each file (multi span signature + 12 bytes data) - // the number of bytes to add: central dir size - total to remove; - DWORD uToGrow = GetSize(true) - (4 + m_info.m_uEntriesNumber * (4 + 12)); - if (uVolumeFree >= uToGrow) - // lets make sure it will be one-disk archive - { - // can the operation be done only in the buffer? - if (!m_pStorage->m_iBytesWritten && // no bytes on the disk yet - (m_pStorage->GetFreeInBuffer() >= uToGrow)) // is the buffer big enough? - { - RemoveDataDescr(true); - bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later - } - else - { - m_pStorage->Flush(); - if (RemoveDataDescr(false)) - bDontAllowDiskChange = true; // if the disk change occurs somehow, we'll throw an error later - } - } - } - - try - { - WriteHeaders(pCallback, bDontAllowDiskChange || !m_pStorage->IsSpanMode()); - - m_info.m_uThisDisk = (WORD)m_pStorage->GetCurrentDisk(); - DWORD uSize = WriteCentralEnd(); - if (bDontAllowDiskChange) - { - if (m_pStorage->GetCurrentDisk() != 0) - ThrowError(CZipException::badZipFile); - } - // if after adding a central directory there is a disk change, - // update the information and write it again - if (m_info.m_uThisDisk != m_pStorage->GetCurrentDisk()) - { - m_info.DiskChange(m_pStorage->GetCurrentDisk()); - - if (m_pStorage->m_uBytesInWriteBuffer >= uSize) - // if the data is still in the buffer, simply remove it - m_pStorage->m_uBytesInWriteBuffer -= uSize; - else - { - m_pStorage->Flush(); - m_pStorage->m_iBytesWritten -= uSize; - m_pStorage->m_pFile->SeekToBegin(); - } - - WriteCentralEnd(); - } - } - catch (...) - { - if (bDontAllowDiskChange) - { - m_pStorage->FinalizeSpan(); - m_info.m_uThisDisk = 0; - } - throw; - } - m_info.m_bOnDisk = true; -} - -void CZipCentralDir::WriteHeaders(CZipActionCallback* pCallback, bool bOneDisk) -{ - m_info.m_uDiskEntriesNo = 0; - m_info.m_uDiskWithCD = (WORD)m_pStorage->GetCurrentDisk(); - m_info.m_uOffset = m_pStorage->GetPosition() - m_info.m_uBytesBeforeZip; - if (!m_info.m_uEntriesNumber) - return; - - WORD iDisk = m_info.m_uDiskWithCD; - int iStep = 0; // for the compiler - - if (pCallback) - { - pCallback->Init(); - pCallback->SetTotal(m_info.m_uEntriesNumber); - iStep = CZipActionCallback::m_iStep;// we don't want to wait forever - } - - int iAborted = 0; - for (int i = 0; i < m_info.m_uEntriesNumber; i++) - { - CZipFileHeader* pHeader = (*this)[i]; - - - CZipString szRemember; - if (m_bConvertAfterOpen) - // if CZipArchive::Flush is called we will be still using the archive, so restore changed name - szRemember = pHeader->GetFileName(); - - ConvertFileName(false, true, pHeader); - m_info.m_uSize += pHeader->Write(m_pStorage); - - if (m_bConvertAfterOpen) - pHeader->SetFileName(szRemember); - - if (m_pStorage->GetCurrentDisk() != iDisk) - { - m_info.m_uDiskEntriesNo = 1; - iDisk = (WORD)m_pStorage->GetCurrentDisk(); - // update the information about the offset and starting disk if the - // first header was written on the new disk - if (i == 0) - { - m_info.m_uOffset = 0; - m_info.m_uDiskWithCD = iDisk; - } - } - else - m_info.m_uDiskEntriesNo++; - if (pCallback && !(i%iStep)) - if (!pCallback->Callback(iStep)) - { - - if (bOneDisk) - { - if (!m_pStorage->IsSpanMode()) - m_pStorage->EmptyWriteBuffer(); - else - m_pStorage->Flush(); // must be flush before - flush was not called in span mode - - // remove saved part from the disk - m_pStorage->m_pFile->SetLength(m_info.m_uBytesBeforeZip + m_info.m_uOffset); -// We can now abort safely - iAborted = CZipException::abortedSafely; - } - else - iAborted = CZipException::abortedAction; - break; - } - } - - if (pCallback) - pCallback->CallbackEnd(); - - if (iAborted) - ThrowError(iAborted); -} - -DWORD CZipCentralDir::WriteCentralEnd() -{ - DWORD uSize = GetSize(); - CZipAutoBuffer buf(uSize); - WORD uCommentSize = (WORD)m_pszComment.GetSize(); - memcpy(buf, m_gszSignature, 4); - memcpy(buf + 4, &m_info.m_uThisDisk, 2); - memcpy(buf + 6, &m_info.m_uDiskWithCD, 2); - memcpy(buf + 8, &m_info.m_uDiskEntriesNo, 2); - memcpy(buf + 10, &m_info.m_uEntriesNumber, 2); - memcpy(buf + 12, &m_info.m_uSize, 4); - memcpy(buf + 16, &m_info.m_uOffset, 4); - memcpy(buf + 20, &uCommentSize, 2); - memcpy(buf + 22, m_pszComment, uCommentSize); - m_pStorage->Write(buf, uSize, true); - return uSize; -} - -void CZipCentralDir::RemoveAll() -{ - m_findarray.RemoveAll(); - RemoveHeaders(); -} - -void CZipCentralDir::RemoveFile(CZipFileHeader* pHeader, int iIndex, bool bShift) -{ - - if (iIndex == -1) - { - int iCount = m_headers.GetSize(); - for (int i = 0; i < iCount; i++) - if (pHeader == m_headers[i]) - { - iIndex = i; - break; - } - } - ASSERT(iIndex != -1 || pHeader); - if (!pHeader) - pHeader = m_headers[iIndex]; - - if (m_bFindFastEnabled) - { - int i = FindFileNameIndex(pHeader->GetFileName()); - ASSERT(i != -1); - int uIndex = m_findarray[i].m_uIndex; - m_findarray.RemoveAt(i); - // shift down the indexes - - if (bShift) - { - int iSize = m_findarray.GetSize(); - for (int j = 0; j < iSize; j++) - { - if (m_findarray[j].m_uIndex > uIndex) - m_findarray[j].m_uIndex--; - } - } - } - - - - if (iIndex != -1) - { - delete pHeader; - m_headers.RemoveAt(iIndex); - } - -} - - -DWORD CZipCentralDir::GetSize(bool bWhole) const -{ - DWORD uHeaders = 0; - int iCount = m_headers.GetSize(); - if (bWhole) - { - for (int i = 0; i < iCount; i++) - { - const CZipFileHeader* pHeader = m_headers[i]; - uHeaders += pHeader->GetSize(); - } - } - return CENTRALDIRSIZE + m_pszComment.GetSize() + uHeaders; -} - -bool CZipCentralDir::RemoveDataDescr(bool bFromBuffer) -{ - ziparchv::CZipFileMapping fm; - char* pFile; - DWORD uSize; - if (bFromBuffer) - { - uSize = m_pStorage->m_uBytesInWriteBuffer; - pFile = m_pStorage->m_pWriteBuffer; - } - else - { - uSize = m_pStorage->m_pFile->GetLength(); - // we cannot use CZipMemFile in multidisk archive - // so it MUST be CZipFile - if (!fm.CreateMapping(static_cast(m_pStorage->m_pFile))) - return false; - pFile = fm.GetMappedMemory(); - } - - DWORD uOffsetToChange = 4; - DWORD uPosInBuffer = 0; - DWORD uExtraHeaderLen; - int iCount = m_headers.GetSize(); - for (int i = 0; i < iCount; i++) - { - // update the flag value in the local and central header -// int uDataDescr = (m_headers[i]->m_uFlag & 8) ? (4 + 12) : 0; - - CZipFileHeader* pHeader = m_headers[i]; - - - char* pSour = pFile + pHeader->m_uOffset; - - if (!pHeader->IsEncrypted()) - { - // removing data descriptor - pHeader->m_uFlag &= ~8; - // update local header: - // write modified flag in the local header - memcpy(pSour + 6, &pHeader->m_uFlag, 2); - uExtraHeaderLen = 4/*ext. header signature*/ + 12/*data descriptor*/; - } - else - // do not remove data descriptors from encrypted files - uExtraHeaderLen = 0; - - // update crc32 and sizes' values - pHeader->GetCrcAndSizes(pSour+ 14); - - DWORD uToCopy = (i == (iCount - 1) ? uSize : m_headers[i + 1]->m_uOffset) - - pHeader->m_uOffset - uExtraHeaderLen; - - memmove(pFile + uPosInBuffer, pSour, uToCopy); - - uPosInBuffer += uToCopy; - pHeader->m_uOffset -= uOffsetToChange; - uOffsetToChange += uExtraHeaderLen; - } - - if (bFromBuffer) - m_pStorage->m_uBytesInWriteBuffer = uPosInBuffer; - else - { - m_pStorage->m_iBytesWritten = uPosInBuffer; - fm.RemoveMapping(); - m_pStorage->m_pFile->SetLength(uPosInBuffer); - } - return true; -} - -void CZipCentralDir::RemoveHeaders() -{ - int iCount = m_headers.GetSize(); - for (int i = 0; i < iCount; i++) - delete m_headers[i]; - m_headers.RemoveAll(); -} - - - -void CZipCentralDir::ConvertAll() -{ - ASSERT(!m_bConvertAfterOpen); - int iCount = m_headers.GetSize(); - for (int i = 0; i < iCount; i++) - ConvertFileName(true, false, m_headers[i]); - m_bConvertAfterOpen = true; -} - -void CZipCentralDir::BuildFindFastArray( bool bCaseSensitive ) -{ - m_findarray.RemoveAll(); - m_bCaseSensitive = bCaseSensitive; - m_pCompare = GetCZipStrCompFunc(bCaseSensitive); - int iCount = m_headers.GetSize(); - if (!m_bConvertAfterOpen) - { - for (int i = 0; i < iCount; i++) - { - CZipFileHeader fh = *m_headers[i]; - ConvertFileName(true, false, &fh); - InsertFindFastElement(&fh, i); // this method requires the name to be already converted - } - } - else - for (int i = 0; i < iCount; i++) - InsertFindFastElement(m_headers[i], i); -} - -void CZipCentralDir::EnableFindFast(bool bEnable, bool bCaseSensitive) -{ - if (m_bFindFastEnabled == bEnable) - return; - m_bFindFastEnabled = bEnable; - if (bEnable) - BuildFindFastArray(bCaseSensitive); - else - m_findarray.RemoveAll(); -} - -int CZipCentralDir::FindFile(LPCTSTR lpszFileName, bool bCaseSensitive, bool bSporadically, bool bFileNameOnly) -{ - // this is required for fast finding and is done only once - if (!m_bConvertAfterOpen) - { - TRACE(_T("%s(%i) : Converting all the filenames.\n"),__FILE__,__LINE__); - ConvertAll(); - } - if (!m_bFindFastEnabled) - EnableFindFast(true, bSporadically ? !bCaseSensitive : bCaseSensitive); - int iResult = -1; - if (bFileNameOnly) - { - // a non-effective search (treat an array as unsorted) - int iSize = m_findarray.GetSize(); - for (int i = 0; i < iSize; i++) - { - CZipString sz = GetProperHeaderFileName(m_findarray[i].m_pHeader); - CZipPathComponent::RemoveSeparators(sz); // to find a dir - CZipPathComponent zpc(sz); - sz = zpc.GetFileName(); - if ((sz.*m_pCompare)(lpszFileName) == 0) - { - iResult = i; - break; - } - } - } - else if (bCaseSensitive == m_bCaseSensitive) - iResult = FindFileNameIndex(lpszFileName); - else - { - if (bSporadically) - { - // a non-effective search (treat an array as unsorted) - int iSize = m_findarray.GetSize(); - for (int i = 0; i < iSize; i++) - if (CompareElement(lpszFileName, (WORD)i) == 0) - { - iResult = i; - break; - } - } - else - { - BuildFindFastArray(bCaseSensitive); - iResult = FindFileNameIndex(lpszFileName); - } - } - return iResult == -1 ? -1 : m_findarray[iResult].m_uIndex; -} - -void CZipCentralDir::InsertFindFastElement(CZipFileHeader* pHeader, WORD uIndex) -{ - CZipString fileName = pHeader->GetFileName(); - int iSize = m_findarray.GetSize(); - - // Our initial binary search range encompasses the entire array of filenames: - int start = 0; - int end = iSize; - - // Keep halving our search range until we find the right place - // to insert the new element: - while ( start < end ) - { - // Find the midpoint of the search range: - int midpoint = ( start + end ) / 2; - - // Compare the filename with the filename at the midpoint of the current search range: - int result = CompareElement(fileName, (WORD)midpoint); - - // If our filename is larger, it must fall in the first half of the search range: - if ( result > 0 ) - { - end = midpoint; - } - - // If it's smaller, it must fall in the last half: - else if ( result < 0 ) - { - start = midpoint + 1; - } - - // If they're equal, we can go ahead and insert here: - else - { - start = midpoint; break; - } - } - m_findarray.InsertAt(start, CZipFindFast(pHeader, WORD(uIndex == WORD(-1) ? iSize : uIndex /* just in case */))); -} - -int CZipCentralDir::FindFileNameIndex(LPCTSTR lpszFileName) const -{ - int start = 0; - int end = m_findarray.GetUpperBound(); - - // Keep halving our search range until we find the given element: - while ( start <= end ) - { - // Find the midpoint of the search range: - int midpoint = ( start + end ) / 2; - - // Compare the given filename with the filename at the midpoint of the search range: - int result = CompareElement(lpszFileName, (WORD)midpoint); - - // If our filename is smaller, it must fall in the first half of the search range: - if ( result > 0 ) - { - end = midpoint - 1; - } - - // If it's larger, it must fall in the last half: - else if ( result < 0 ) - { - start = midpoint + 1; - } - - // If they're equal, return the result: - else - { - return midpoint; - } - } - - // Signal failure: - return -1; -} - -void CZipCentralDir::RenameFile(WORD uIndex, LPCTSTR lpszNewName) -{ - CZipFileHeader* pHeader = m_headers[uIndex]; - pHeader->SetFileName(lpszNewName); - if (!m_bConvertAfterOpen) - ZipCompatibility::FileNameUpdate(*pHeader, false); - if (m_bFindFastEnabled) - BuildFindFastArray(m_bCaseSensitive); -} \ No newline at end of file diff --git a/harbour/contrib/hbziparch/zipcentraldir.h b/harbour/contrib/hbziparch/zipcentraldir.h deleted file mode 100644 index c7c6132ec2..0000000000 --- a/harbour/contrib/hbziparch/zipcentraldir.h +++ /dev/null @@ -1,554 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipCentralDir.h $ -// $Archive: /ZipArchive/ZipCentralDir.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipCentralDir.h -* Interface for the CZipCentralDir class. -* -*/ - -#if !defined(AFX_CENTRALDIR_H__859029E8_8927_4717_9D4B_E26E5DA12BAE__INCLUDED_) -#define AFX_CENTRALDIR_H__859029E8_8927_4717_9D4B_E26E5DA12BAE__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#if (_MSC_VER > 1000) && (defined ZIP_HAS_DLL) - #pragma warning( disable : 4251 ) // needs to have dll-interface to be used by clients of class -#endif - -#include "zipexception.h" -#include "zipfileheader.h" -#include "zipautobuffer.h" -#include "zipcollections.h" -#include "zipcompatibility.h" -#include "ZipExport.h" -#define ZIPARCHIVE_DATADESCRIPTOR_LEN 12 - -/** - A class representing the central directory record in the archive. -*/ -class ZIP_API CZipCentralDir -{ -public: - /** - Used in fast finding files by the filename. - A structure for the internal use only. - \see CZipCentralDir::m_findarray - \see CZipArchive::GetFindFastElement - \see CZipArchive::FindFile - \see CZipArchive::EnableFindFast - */ - struct ZIP_API CZipFindFast - { - CZipFindFast() - { - m_uIndex = 0; - m_pHeader= NULL; - } - CZipFindFast(CZipFileHeader* pHeader, WORD uIndex):m_pHeader(pHeader), m_uIndex(uIndex){} - /** - A pointer to the structure in CZipCentralDir. We extract a name from it. - */ - CZipFileHeader* m_pHeader; - - /** - The index in the central directory of the \e m_pHeader. - */ - WORD m_uIndex; - }; - - - /** - Stores general information about the central directory record. - */ - struct ZIP_API Info - { - DWORD m_uCentrDirPos; ///< the position of the beginning of the central directory (as located by #Locate) - DWORD m_uBytesBeforeZip;///< The number of bytes before the actual zip archive in a file. It is non-zero for self-extracting archives. - WORD m_uThisDisk; ///< number of the disk with the central directory end record (the number of disks in the disk-spanning archive) - WORD m_uDiskWithCD; ///< number of the disk with the start of the central directory - WORD m_uDiskEntriesNo; ///< total number of entries in the central dir on this disk - WORD m_uEntriesNumber; ///< total number of entries in the central dir - DWORD m_uSize; ///< size of the central directory (valid only if #m_bOnDisk is \c true; use #GetSize instead) - DWORD m_uOffset; ///< offset of start of central directory with respect to the starting disk number - ///< (as written in the central directory record); - ///< valid only if #m_bOnDisk is \c true - bool m_bOnDisk; ///< \c true if the central directory is physically present in the archive -#if !defined(__GNUC__) - protected: - friend CZipCentralDir; -#endif - - bool CheckIfOK_1() - { - return ((DWORD)m_uCentrDirPos >= m_uOffset + m_uSize); - } - void SetBytesBeforeZip(bool bIsSpan) - { - m_uBytesBeforeZip = bIsSpan ? 0 : m_uCentrDirPos - m_uSize - m_uOffset; - } - bool CheckIfOK_2() - { - return (m_uSize || !m_uEntriesNumber) && (m_uEntriesNumber || !m_uSize); - } - void DiskChange(int iCurrentDisk) - { - m_uThisDisk = (WORD)iCurrentDisk; - if (m_uEntriesNumber) - { - m_uDiskEntriesNo = 0; - } - else - { - m_uDiskWithCD = m_uThisDisk; - m_uOffset = 0; - } - } - }; - - CZipCentralDir(); - virtual ~CZipCentralDir(); - - static char m_gszSignature[]; ///< central dir signature - - char m_szSignature[4]; ///< end of central dir signature (must be 0x06054b50) - - CZipAutoBuffer m_pszComment; ///< the archive comment - CZipAutoBuffer m_pLocalExtraField; ///< a local extra field - CZipFileHeader* m_pOpenedFile; ///< points to a currently opened file or NULL if no file is opened - - /** - Called by CZipArchive::OpenInternal. - */ - void Init(); - - /** - Read the central directory from the archive. - \note Throws exceptions. - */ - void Read(); - - /** - Open the file. - \param uIndex - zero-based index of the file to open - \note Throws exceptions. - */ - void OpenFile(WORD uIndex); - -/** - Test if the given file header index is valid. - \param uIndex - a zero-based index - \return \c true if the file with the given index exists inside the archive; otherwise \c false; -*/ - bool IsValidIndex(int uIndex)const; - -/** - Remove the file header from the central directory. - \param pHeader - the header to remove - \param iIndex if index is not known set it to -1 - \param bShift - \note Throws exceptions. -*/ - void RemoveFile(CZipFileHeader* pHeader, int iIndex = -1, bool bShift = true); - - - /** - Remove last file from the central directory. - - */ - void RemoveLastFile(CZipFileHeader* pHeader = NULL, int iIndex = -1) - { - if (iIndex == -1) - { - iIndex = m_headers.GetSize() - 1; - if (iIndex == -1) - return; - } - if (!pHeader) - pHeader = m_headers[iIndex]; - DWORD uNewSize = pHeader->m_uOffset + GetBytesBefore(); - // then remove - RemoveFile(pHeader, iIndex); - - m_pStorage->Flush(); - m_pStorage->m_pFile->SetLength(uNewSize); - m_info.m_bOnDisk = false; // it is true when AutoFlush is set to true - } - - - /** - Remove all files - \note Throws exceptions. - */ - void RemoveAll(); -/** - Cleanup the structure. - \param bEverything - - \c true - clear some attributes and remove all the file headers from memory - - \c false - do not remove the file headers. It is called in that manner - from CZipArchive::CloseFileAfterTestFailed so that the - next file can be tested for the integrity - \see CZipArchive::CloseFileAfterTestFailed -*/ - void Clear(bool bEverything = true); - -/** - Add a new file to the central directory. - \param header - copy data from it to the new file header - \param iReplaceIndex if different from -1, the index of the file to be replaced - \return the pointer to the new header - \note Throws exceptions. -*/ - CZipFileHeader* AddNewFile(const CZipFileHeader & header, int iReplaceIndex = -1); - - /** - return the header filename, converted if needed - */ - CZipString GetProperHeaderFileName(const CZipFileHeader* pHeader) const - { - if (!m_bConvertAfterOpen) - { - CZipFileHeader fh = *pHeader; - ConvertFileName(true, false, &fh); - return fh.GetFileName(); - } - else - return pHeader->GetFileName(); - } - -/** - Remove physically the central directory from the archive. - Called during adding or deleting files. - \note Throws exceptions. -*/ - void RemoveFromDisk(); - -/** - Get the central directory size. - \param bWhole - if \c true, include the size of the file headers - \return the size of the central directory - \see CZipArchive::GetCentralDirSize -*/ - DWORD GetSize(bool bWhole = false) const; - - /** - Close a file inside archive opened for reading. - \param bAfterException \c true if closing after exception - \note Throws exceptions. - */ - void CloseFile(bool bAfterException = false); - - /** - Close a file inside archive opened for reading. - \note Throws exceptions. - */ - void CloseNewFile(); - - /** - Write the central directory to the archive. - \note Throws exceptions. - */ - void Write(CZipActionCallback* pCallback); - - /** - \see CZipArchive::EnableFindFast - */ - void EnableFindFast(bool bEnable, bool bCaseSensitive); - - /** - \see CZipArchive::FindFile - \note \e bSporadically set to \c false rebuilds #m_findarray if necessary - */ - int FindFile(LPCTSTR lpszFileName, bool bCaseSensitive, bool bSporadically, bool bFileNameOnly); - - - /** - \see CZipArchive::GetFindFastIndex - */ - int GetFindFastIndex(int iFindFastIndex)const - { - if (!IsValidIndex(iFindFastIndex) || !m_bFindFastEnabled) - { - // ASSERT(FALSE); // - return -1; - } - - return m_findarray[iFindFastIndex].m_uIndex; - } - - /** - Points to CZipArchive::m_storage. - */ - CZipStorage* m_pStorage; - - - /** - The size of the buffer used in searching for the central dir. - Set before opening the archive. - It is usually set with CZipArchive::SetAdvanced - (specify this value as the third argument). - \see CZipArchive::SetAdvanced - */ - int m_iBufferSize; - - - - - /** - Holds all the files inside archive info. - \see CZipFileHeader - */ - CZipArray m_headers; - - CZipFileHeader* operator[](int iIndex) - { - return m_headers[iIndex]; - } - const CZipFileHeader* operator[](int iIndex) const - { - return m_headers[iIndex]; - } - - - /** - - If \c true, the conversion of the filenames takes - place after opening the archive (after reading the central directory - from the file), and before writing the central directory back to - the archive. - - If \c false, the conversion takes place on each call to CZipArchive::GetFileInfo - - Change is value with CZipArchive::SetConvertAfterOpen. - - Set it to \c true when you plan to use CZipArchive::FindFile or get the stored files information.
- Set it to \c false when you plan mostly to modify the archive. - - \b Default: \c true - \note Set it before opening the archive. - \see CZipArchive::SetConvertAfterOpen - \see ConvertFileName - */ - bool m_bConvertAfterOpen; - - -/** - Convert the filename of the CZipFileHeader depending on the current system - and the system the zip file was created on (change slash to backslash or - vice versa, perform ANSI-OEM conversion if necessary). - \param bFromZip - if \c true, convert from archive format - \param bAfterOpen - if \c true, called after opening the archive or before closing - \param pHeader - the header to have filename converted; if \c NULL convert the currently - opened file - \see ZipCompatibility::FileNameUpdate - \see m_bConvertAfterOpen -*/ - void ConvertFileName(bool bFromZip, bool bAfterOpen, CZipFileHeader* pHeader = NULL) const - { - if (bAfterOpen != m_bConvertAfterOpen) - return; - if (!pHeader) - { - pHeader = m_pOpenedFile; - ASSERT(pHeader); - } - ZipCompatibility::FileNameUpdate(*pHeader, bFromZip); - } - -/** - Convert all the filenames to the system form. - Called by CZipArchive::FindFile - \see CZipArchive::FindFile -*/ - void ConvertAll(); - -/** - \param lpszFileName - the name of the file to find, must be exactly the same (apart from case) - as it appears in the archive - \return the index in #m_findarray with the appropriate CZipFindFast structure - or \c -1 if there is no file with the given name - \see CZipArchive::FindFile -*/ - int FindFileNameIndex(LPCTSTR lpszFileName) const; - - DWORD GetBytesBefore() const {return m_info.m_uBytesBeforeZip;} - /** - Get the information about the central directory - */ - void GetInfo(Info& info) const {info = m_info;} - /** - \return the value of m_bFindFastEnabled - */ - bool IsFindFastEnabled(){return m_bFindFastEnabled;} - /** - Called by CZipArchive::RenameFile - */ - void RenameFile(WORD uIndex, LPCTSTR lpszNewName); -protected: - /** - Sort the files inside the archive headers by the order in the archive. - */ - void SortHeaders(); - static int CompareHeaders(const void *pArg1, const void *pArg2) - { - CZipFileHeader* pw1 = *(CZipFileHeader**)pArg1; - CZipFileHeader* pw2 = *(CZipFileHeader**)pArg2; - if ((pw1->m_uOffset < pw2->m_uOffset && pw1->m_uDiskStart == pw2->m_uDiskStart) - || (pw1->m_uDiskStart < pw2->m_uDiskStart)) - return -1; - else if ((pw1->m_uOffset > pw2->m_uOffset && pw1->m_uDiskStart == pw2->m_uDiskStart) - || (pw1->m_uDiskStart > pw2->m_uDiskStart)) - return 1; - else - { - ASSERT(FALSE); - // two files with the same offsets on the same disk??? - CZipException::Throw(CZipException::badZipFile); - return 0; // just for the compiler comfort - } - } - - -/** - Build #m_findarray. -*/ - void BuildFindFastArray( bool bCaseSensitive ); - - /** - Used in fast finding files by the filename. - \see CZipFindFast - \see m_bFindFastEnabled - \see CZipArchive::FindFile - */ - CZipArray m_findarray; - - /** - If \c true, the there is an additional array build, to speed up the - finding process - CZipArchive::FindFile uses this array to perform a - binary search. - \b Default: \c false - \see CZipArchive::EnableFindFast - \see CZipArchive::FindFile - \see CZipCentralDir::m_findarray - */ - bool m_bFindFastEnabled; - - - -/** - The \e lpszFileName and \e bCaseSensitive arguments - are the same as in the #FindFileNameIndex. The function get CZipFindFast - structure pointed by \e uIndex and compares the filename of CZipFileHeader - class stored in this structure with \e lpszFileName. - \param lpszFileName - \param uIndex - the index from #m_findarray - \return - - 0 if the filenames are the same - - < 0 if the filename stored in the array is less than \e lpszFileName - - > 0 if the filename stored in the array is greater than \e lpszFileName -*/ - int CompareElement(LPCTSTR lpszFileName, WORD uIndex) const - { - return (m_findarray[uIndex].m_pHeader->GetFileName().*m_pCompare)(lpszFileName); - } -/** - Insert a new CZipFindFast element to the #m_findarray. - Initialize CZipFindFast object with \e pHeader and \e uIndex values. -*/ - void InsertFindFastElement(CZipFileHeader* pHeader, WORD uIndex); - - - - /** - A compare function (Collate or CollateNoCase) set once so as not - to check every time which one to use
- ZIPSTRINGCOMPARE is defined in CZipString.h as:
- typedef int (CZipString::*ZIPSTRINGCOMPARE)( LPCTSTR ) const; - */ - ZIPSTRINGCOMPARE m_pCompare; - - /** - The way the m_findarray is sorted - */ - bool m_bCaseSensitive; - - /** - \see Info - */ - Info m_info; - - /** - \return the location of the beginning of the central dir end record in the archive - \note Throws exceptions. - */ - DWORD Locate(); - /** - Read the file headers from the file. - \note Throws exceptions. - */ - void ReadHeaders(); - - /** - Free the memory allocated for the CZipFileHeader structures. - */ - void RemoveHeaders(); -/** - Remove data descriptors from the write buffer in the disk spanning volume - that turned out to be one-disk only. - We do not remove them from password encrypted files. - - \param bFromBuffer - if \c true, remove from the buffer in memory otherwise from the file on a disk - \return \c false if the file mapping to memory was not successful - Can happen only when \e bFormBuffer is \c false. - \note Throws exceptions. -*/ - bool RemoveDataDescr(bool bFromBuffer); -/** - Write the file headers to the archive. - \note Throws exceptions. -*/ - void WriteHeaders(CZipActionCallback* pCallback, bool bOneDisk); -/** - Write the central directory end record. - \return the size of the record - \note Throws exceptions. -*/ - DWORD WriteCentralEnd(); - -/** - Throw an exception with the given code. - \param err - \see CZipException::Throw -*/ - void ThrowError(int err) const; - - -}; - - -#endif // !defined(AFX_CENTRALDIR_H__859029E8_8927_4717_9D4B_E26E5DA12BAE__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipcollections.h b/harbour/contrib/hbziparch/zipcollections.h deleted file mode 100644 index 5ab4b6bb38..0000000000 --- a/harbour/contrib/hbziparch/zipcollections.h +++ /dev/null @@ -1,171 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $RCSfile$ -// $Revision$ $Name$ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyrighted 2000-2005 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#ifndef ZIPCOLLECTIONS_DOT_H -#define ZIPCOLLECTIONS_DOT_H - -#if _MSC_VER > 1000 - #pragma warning( push, 3 ) // STL "requirements" - #pragma warning (disable : 4284) //return type for 'identifier::operator >' is not a UDT or reference to a UDT. Will produce errors if applied using infix notation - #pragma warning (disable : 4018) //'expression' : signed/unsigned mismatch -#endif - -#include -#include -#include -#include -#include - -#include "zipstring.h" -#include "ZipExport.h" - -template -class CZipArray : private std::vector -{ -public: - typedef typename std::vector::iterator iterator; - typedef typename std::vector inherited; -protected: - iterator GetIterFromIndex(int uIndex) - { - iterator iter = this->begin(); - iter += uIndex; - // int t = 0; while (t != uIndex) {iter++;t++;} - return iter; - } -public: - void Sort(bool bAscending) - { - if (bAscending) - std::sort (this->begin (), this->end (), std::less ()); - else - std::sort (this->begin (), this->end (), std::greater ()); - } - int GetSize() const{return (int)this->size(); } - int GetUpperBound() const {return this->size() - 1;} - int Add(const TYPE& x) {push_back(x);return GetUpperBound();} - void RemoveAll() {this->clear();} - void RemoveAt(int uIndex) { erase(GetIterFromIndex(uIndex));} - void InsertAt(int uIndex, const TYPE& x){insert(GetIterFromIndex(uIndex), x);} -#ifndef _MSC_VER - TYPE& operator[](int iIndex) - { - return inherited::operator[](iIndex); - } - TYPE operator[](int iIndex) const - { - return inherited::operator[](iIndex); - } -#else - using inherited::operator[]; -#endif -}; - - -typedef CZipArray CZipStringArray; -typedef CZipArray CZipWordArray; - - -template -class ZIP_API CZipPtrList : private std::list -{ - -public: - typedef typename std::list::iterator iterator; - typedef typename std::list::const_iterator const_iterator; - int GetCount() const {return this->size();} - void AddTail(const TYPE& x){push_back(x);} - void AddHead(const TYPE& x){push_front(x);} - void RemoveHead() {this->pop_front();} - void RemoveTail() {this->pop_back();} - void RemoveAll() {this->clear();} - TYPE& GetHead() {return this->front();} - TYPE GetHead() const {return this->front();} - TYPE& GetTail() {return this->back();} - TYPE GetTail() const {return this->back();} - iterator GetHeadPosition() { return this->begin();} - const_iterator GetHeadPosition() const { return this->begin();} - iterator GetTailPosition() { return this->back();} - TYPE& GetNext(iterator& pos) { return *pos++;} - const TYPE GetNext(const_iterator& pos) const{ return *pos++;} - TYPE& GetPrev(iterator& pos) { return *pos--;} - TYPE GetPrev(iterator& pos) const{ return *pos--;} - iterator Find(TYPE& x) { return std::find(this->begin(), this->end(), x);} - void RemoveAt(iterator& pos) { erase(pos);} - bool IteratorValid(const_iterator &iter) const - { - return iter != this->end(); - } - bool IteratorValid(iterator &iter) - { - return iter != this->end(); - } - iterator FindIndex(int iIndex) - { - iterator iter = this->begin(); - int t = 0; while (t != iIndex) {iter++;t++;} - return iter; - } - const_iterator FindIndex(int iIndex) const - { - const_iterator iter = this->begin(); - int t = 0; while (t != iIndex) {iter++;t++;} - return iter; - } - TYPE& GetAt(const iterator& pos) { return *pos;} - TYPE GetAt(const_iterator& pos) const{ return *pos;} - -}; - -// simplified and partial only -template -class ZIP_API CZipMap : private std::map -{ -public: - typedef typename std::map::const_iterator const_iterator; - typedef typename std::map, std::allocator > >::value_type v_type; - void SetAt( KEY key, VALUE newValue) - { - insert(v_type(key, newValue)); - } - BOOL RemoveKey( KEY key ) - { - return erase(key) != 0; - } - BOOL Lookup( KEY key, VALUE& rValue ) const - { - const_iterator iter = find(key); - -#if (__GNUC__ >= 3) // I'm not sure which version precisely should be put here - if (iter == std::map::end()) -#else - if (iter == end()) -#endif - return FALSE; - else - { - rValue = iter->second; - return TRUE; - } - } -}; - -#if defined(_MSC_VER) && (_MSC_VER > 1100) - #pragma warning( pop) -#endif - -#endif /* ZIPCOLLECTIONS_DOT_H */ - diff --git a/harbour/contrib/hbziparch/zipcompatibility.cpp b/harbour/contrib/hbziparch/zipcompatibility.cpp deleted file mode 100644 index 4fee9a7ff6..0000000000 --- a/harbour/contrib/hbziparch/zipcompatibility.cpp +++ /dev/null @@ -1,214 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipCompatibility.cpp $ -// $Archive: /ZipArchive/ZipCompatibility.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#include "stdafx.h" -#include "zipcompatibility.h" -#include "zipplatform.h" -#include "zipexception.h" -#include "zipautobuffer.h" -#include "zipfileheader.h" -enum iInternalAttr -{ - attROnly = 0x01, - attHidd = 0x02, - attSys = 0x04, - attDir = 0x10, - attArch = 0x20 -}; -// *********************** WINDOWS ************************** -#ifndef _WIN32 - #define FILE_ATTRIBUTE_READONLY 0x00000001 - #define FILE_ATTRIBUTE_HIDDEN 0x00000002 - #define FILE_ATTRIBUTE_SYSTEM 0x00000004 - #define FILE_ATTRIBUTE_DIRECTORY 0x00000010 - #define FILE_ATTRIBUTE_ARCHIVE 0x00000020 -#endif -// *********************** UINX ************************** -#define USER_PERMISSIONS_MASK 0x01C00000 -#define EXTRACT_USER_PERMISSIONS(x) ((x & USER_PERMISSIONS_MASK) >> 22) -#define CREATE_USER_PERMISSIONS(x) ((x & 0x0007) << 22) - -#define GROUP_PERMISSIONS_MASK 0x00380000 -#define EXTRACT_GROUP_PERMISSIONS ((x & GROUP_PERMISSIONS_MASK) >> 19) -#define CREATE_GROUP_PERMISSIONS(x) ((x & 0x0007) << 19) - -#define OTHER_PERMISSIONS_MASK 0x00070000 -#define EXTRACT_OTHER_PERMISSIONS ((x & OTHER_PERMISSIONS_MASK) >> 16) -#define CREATE_OTHER_PERMISSIONS(x) ((x & 0x0007) << 16) - -#define UNIX_DIRECTORY_ATTRIBUTE 0x40000000 -#define UNIX_FILE_ATTRIBUTE 0x80000000 - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// -using namespace ZipCompatibility; - -typedef DWORD(*conv_func)(DWORD , bool ); - -DWORD AttrDos(DWORD , bool ); -DWORD AttrUnix(DWORD, bool); -DWORD AttrMac(DWORD , bool ); - -// more to come... -conv_func conv_funcs[11] = {AttrDos, - NULL, - NULL, - AttrUnix, - NULL, - NULL, - AttrDos, - AttrMac, - NULL, - NULL, - AttrDos -}; - - - -DWORD ZipCompatibility::ConvertToSystem(DWORD uAttr, int iFromSystem, int iToSystem) -{ - - if (iToSystem != iFromSystem && iFromSystem < 11 && iToSystem < 11) - { - conv_func p = conv_funcs[iFromSystem], q = conv_funcs[iToSystem]; - if (p && q) - uAttr = q( p(uAttr, true), false); - else - CZipException::Throw(CZipException::platfNotSupp); - } - return uAttr; -} - - -DWORD AttrDos(DWORD uAttr, bool ) -{ - return uAttr; -} - - - -DWORD AttrUnix(DWORD uAttr, bool bFrom) -{ - DWORD uNewAttr = 0; - if (bFrom) - { - if (uAttr & UNIX_DIRECTORY_ATTRIBUTE) - uNewAttr = attDir; - - uAttr = EXTRACT_USER_PERMISSIONS (uAttr); - - // we may set archive attribute if the file hasn't the execute permissions - // - if (!(uAttr & 1)) - uNewAttr |= attArch ; - - if (!(uAttr & 2)) - uNewAttr |= attROnly; - - if (!(uAttr & 4)) - uNewAttr |= attHidd; - } - else - { - - uNewAttr = 0; // we cannot assume that if the file hasn't the archive attribute set - - //then it is executable and set execute permissions - - if (!(uAttr & attHidd)) - uNewAttr |= (CREATE_OTHER_PERMISSIONS (4) | - CREATE_GROUP_PERMISSIONS (4)) - | CREATE_USER_PERMISSIONS (4); - - if (!(uAttr & attROnly)) - uNewAttr |= (CREATE_GROUP_PERMISSIONS (2) | - CREATE_USER_PERMISSIONS (2)); - if (uAttr & attDir) - uNewAttr |= UNIX_DIRECTORY_ATTRIBUTE | attDir; - else - uNewAttr |= UNIX_FILE_ATTRIBUTE; - - } - - return uNewAttr; -} - -DWORD AttrMac(DWORD uAttr, bool ) -{ - DWORD uNewAttr = uAttr & (attDir | attROnly); -// if (bFrom) -// { -// -// } -// else -// { -// -// } - return uNewAttr; -} - -// ************************************************************************ -ZIPINLINE bool ZipCompatibility::IsPlatformSupported(int iCode) -{ - return iCode == zcDosFat || iCode == zcUnix || iCode == zcMacintosh - || iCode == zcNtfs || iCode == zcOs2Hpfs; -} - - -void ZipCompatibility::FileNameUpdate(CZipFileHeader& header, bool bFromZip) -{ - int iSysHeader = header.GetSystemCompatibility(); - int iCurSystem = ZipPlatform::GetSystemID(); - if (bFromZip) - { - if (iCurSystem == zcDosFat) - SlashBackslashChg(header.m_pszFileName, true); - if (iSysHeader == zcDosFat) - ZipPlatform::AnsiOem(header.m_pszFileName, false); - } - else - { - if (iSysHeader == zcDosFat) - { - ZipPlatform::AnsiOem(header.m_pszFileName, true); - - - } - SlashBackslashChg(header.m_pszFileName, false); - } -} - -void ZipCompatibility::SlashBackslashChg(CZipAutoBuffer& buffer, bool bReplaceSlash) -{ - char t1 = '\\' /*backslash*/, t2 = '/', c1, c2; - if (bReplaceSlash) - { - c1 = t1; - c2 = t2; - } - else - { - c1 = t2; - c2 = t1; - } - for (DWORD i = 0; i < buffer.GetSize(); i++) - { - if (buffer[i] == c2) - buffer[i] = c1; - } - -} diff --git a/harbour/contrib/hbziparch/zipcompatibility.h b/harbour/contrib/hbziparch/zipcompatibility.h deleted file mode 100644 index b453ff5bcc..0000000000 --- a/harbour/contrib/hbziparch/zipcompatibility.h +++ /dev/null @@ -1,107 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipCompatibility.h $ -// $Archive: /ZipArchive/ZipCompatibility.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -/** -* \file ZipCompatibility.h -* ZipCompatibility namespace declaration. -* -*/ - -#if !defined(AFX_ZIPCOMPATIBILITY_H__8E8B9904_84C7_4B22_B364_A10ED0E7DAD6__INCLUDED_) -#define AFX_ZIPCOMPATIBILITY_H__8E8B9904_84C7_4B22_B364_A10ED0E7DAD6__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -class CZipAutoBuffer; -class CZipFileHeader; - -/** - Functions that provides the proper conversion of attributes - and filename strings between different system platforms. -*/ -namespace ZipCompatibility -{ - /** - The codes of the compatibility of the file attribute information. - \see CZipArchive::GetSystemCompatibility - \see CZipFileHeader::GetSystemCompatibility - \see ZipPlatform::GetSystemID - */ - enum ZipPlatforms - { - zcDosFat, ///< MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) - zcAmiga, ///< Amiga - zcVaxVms, ///< VAX/VMS - zcUnix, ///< Unix / Linux - zcVmCms, ///< VM/CMS - zcAtari, ///< Atari ST - zcOs2Hpfs, ///< OS/2 H.P.F.S. - zcMacintosh, ///< Macintosh - zcZsystem, ///< Z-System - zcCpm, ///< CP/M - zcNtfs ///< Windows NTFS - }; - -/** - Check whether the system with the given code is supported by the ZipArchive library. - \param iCode - \link #ZipPlatforms the system code \endlink - \return \c true if supported -*/ - bool IsPlatformSupported(int iCode); - - -/** - Convert the system attributes between different system platforms. - It calls one of the converting functions. - \param uAttr - attributes to convert - \param iFromSystem - system code to convert from - \param iToSystem - system code to convert to - \return the converted attributes - \note Throws exceptions. - \see ZipPlatforms -*/ - DWORD ConvertToSystem(DWORD uAttr, int iFromSystem, int iToSystem); - -/** - Convert the filename of the file inside archive. - This conversion may not change the size of the filename, otherwise an - error may occur in #ReadLocal while comparing the filename sizes. - \param header - the file header to have the filename converted - \param bFromZip - if \c true convert the path from the from it is stored in the archive - to the current system compatible form; otherwise vice-versa. - \see CZipCentralDir::ConvertFileName -*/ void FileNameUpdate(CZipFileHeader& header, bool bFromZip); - -/** - Change the slash to backslash or vice-versa in \e buffer. - \param buffer - \param bReplaceSlash - if \c true, change slash to backslash -*/ - void SlashBackslashChg(CZipAutoBuffer& buffer, bool bReplaceSlash); - -}; - -#endif // !defined(AFX_ZIPCOMPATIBILITY_H__8E8B9904_84C7_4B22_B364_A10ED0E7DAD6__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipexception.cpp b/harbour/contrib/hbziparch/zipexception.cpp deleted file mode 100644 index 575f047354..0000000000 --- a/harbour/contrib/hbziparch/zipexception.cpp +++ /dev/null @@ -1,280 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipException.cpp $ -// $Archive: /ZipArchive/ZipException.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#include "stdafx.h" -#include "zipexception.h" -#include - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// -#ifdef _MFC_VER - IMPLEMENT_DYNAMIC( CZipException, CException) -#endif - -CZipException::CZipException(int iCause, LPCTSTR lpszZipName) -#ifdef _MFC_VER - :CException(TRUE) -#endif -{ - m_iCause = iCause; - - if (lpszZipName) - m_szFileName = lpszZipName; -} - -//CZipException::~CZipException() -#if __GNUC__ >=3 - CZipException::~CZipException() throw() -#else - CZipException::~CZipException() -#endif - -{ - -} - -// inline void CZipException::Throw(int iZipError, LPCTSTR lpszZipName) -// { -// #ifdef _MFC_VER -// throw new CZipException(iZipError, lpszZipName); -// #else -// CZipException e(iZipError, lpszZipName); -// throw e; -// #endif -// MSVC++: ignore "Unreachable code" warning here, it's due to -// optimizations -// } - -int CZipException::ZlibErrToZip(int iZlibError) -{ - switch (iZlibError) - { - case 2://Z_NEED_DICT: - return CZipException::needDict; - case 1://Z_STREAM_END: - return CZipException::streamEnd; - case -1://Z_ERRNO: - return CZipException::errNo; - case -2://Z_STREAM_ERROR: - return CZipException::streamError; - case -3://Z_DATA_ERROR: - return CZipException::dataError; - case -4://Z_MEM_ERROR: - return CZipException::memError; - case -5://Z_BUF_ERROR: - return CZipException::bufError; - case -6://Z_VERSION_ERROR: - return CZipException::versionError; - default: - return CZipException::generic; - } - -} - -#ifdef ZIP_ENABLE_ERROR_DESCRIPTION - -BOOL CZipException::GetErrorMessage(LPTSTR lpszError, UINT nMaxError, - UINT* ) - -{ - if (!lpszError || !nMaxError) - return FALSE; - CZipString sz = GetErrorDescription(); - if (sz.IsEmpty()) - return FALSE; - UINT iLen = sz.GetLength(); - if (nMaxError - 1 < iLen) - iLen = nMaxError - 1; - LPTSTR lpsz = sz.GetBuffer(iLen); -#ifdef _UNICODE - wcsncpy(lpszError, lpsz, iLen); -#else - strncpy(lpszError, lpsz, iLen); -#endif - lpszError[iLen] = _T('\0'); - return TRUE; -} - - -CZipString CZipException::GetErrorDescription() -{ - return GetInternalErrorDescription(m_iCause); -} - - -CZipString CZipException::GetSystemErrorDescription() -{ -#ifdef WIN32 - DWORD x = GetLastError(); - if (x) - { - LPVOID lpMsgBuf; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, x, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR) &lpMsgBuf, 0, NULL); - CZipString sz = (LPCTSTR)lpMsgBuf; - LocalFree(lpMsgBuf); - return sz; - } -#endif - return GetInternalErrorDescription(errno == 0 ? generic : errno, true); -} - -CZipString CZipException::GetInternalErrorDescription(int iCause, bool bNoLoop) -{ - CZipString sz; - switch (iCause) - { - case EROFS: - sz = _T("Read-only file system"); - break; - case ESPIPE: - sz = _T("Illegal seek"); - break; - case ENOSPC: - sz = _T("No space left on device"); - break; - case EFBIG: - sz = _T("File too large"); - break; - case EMFILE: - sz = _T("Too many open files"); - break; - case ENFILE: - sz = _T("File table overflow"); - break; - case EINVAL: - sz = _T("Invalid argument"); - break; - case EISDIR: - sz = _T("Is a directory"); - break; - case ENOTDIR: - sz = _T("Not a directory"); - break; - case ENODEV: - sz = _T("No such device"); - break; - case EXDEV: - sz = _T("Cross-device link"); - break; - case EEXIST: - sz = _T("File exists"); - break; - case EFAULT: - sz = _T("Bad address"); - break; - case EACCES: - sz = _T("Permission denied"); - break; - case ENOMEM: - sz = _T("Not enough space"); - break; - case EBADF: - sz = _T("Bad file number"); - break; - case ENXIO: - sz = _T("No such device or address"); - break; - case EIO: - sz = _T("I/O error"); - break; - case EINTR: - sz = _T("Interrupted system call"); - break; - case ENOENT: - sz = _T("No such file or directory"); - break; - case EPERM: - sz = _T("Not super-user"); - break; - case badZipFile: - sz = _T("Damaged or not a zip file"); - break; - case badCrc: - sz = _T("Crc mismatched"); - break; - case noCallback: - sz = _T("No disk-spanning callback functor set"); - break; - case aborted: - sz = _T("Disk change aborted"); - break; - case abortedAction: - sz = _T("Action aborted"); - break; - case abortedSafely: - sz = _T("Action aborted safely"); - break; - case nonRemovable: - sz = _T("The device selected for the disk spanning archive is non removable"); - break; - case tooManyVolumes: - sz = _T("Limit of the maximum volumes reached (999)"); - break; - case tooLongFileName: - sz = _T("The filename of the file being added to the archive is too long"); - break; - case badPassword: - sz = _T("Incorrect password set for the file being decrypted"); - break; - case dirWithSize: - sz = _T("During testing found the directory with the size greater than 0"); - break; - case internal: - sz = _T("Internal error"); - break; - case notRemoved: - sz.Format(_T("%s (%s)"), _T("Error while removing a file"), (LPCTSTR)GetSystemErrorDescription()); - break; - case notRenamed: - sz.Format(_T("%s (%s)"), _T("Error while renaming a file"), (LPCTSTR)GetSystemErrorDescription()); - break; - case platfNotSupp: - sz = _T("Cannot create the file for the specified platform"); - break; - case cdirNotFound: - sz = _T("The central directory was not found in the archive (or you were trying to open not the last disk of a multi-disk archive)"); - break; - case streamEnd: - sz = _T("Zlib Library error (end of stream)"); - break; - case errNo: - sz = GetInternalErrorDescription(errno != errNo ? errno : generic); - break; - case streamError: - sz = _T("Zlib library error (stream error)"); - break; - case dataError: - sz = _T("Zlib library error (data error)"); - break; - case memError: - sz = _T("Not enough memory"); - break; - case bufError: - sz = _T("Zlib library error (buffer error)"); - break; - case versionError: - sz = _T("Zlib library error (version error)"); - break; - default: - sz = bNoLoop ? _T("Unknown error") :(LPCTSTR) GetSystemErrorDescription(); - } - return sz; -} - -#endif //ZIP_ENABLE_ERROR_DESCRIPTION diff --git a/harbour/contrib/hbziparch/zipexception.h b/harbour/contrib/hbziparch/zipexception.h deleted file mode 100644 index 4b4a87d4e7..0000000000 --- a/harbour/contrib/hbziparch/zipexception.h +++ /dev/null @@ -1,228 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipException.h $ -// $Archive: /ZipArchive/ZipException.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipException.h -* Interface for the CZipException class. -* -*/ - - -#if !defined(AFX_ZIPEXCEPTION_H__E3546921_D728_11D3_B7C7_E77339672847__INCLUDED_) -#define AFX_ZIPEXCEPTION_H__E3546921_D728_11D3_B7C7_E77339672847__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#pragma warning( push ) -#pragma warning (disable:4702) // disable "Unreachable code" warning in Throw function in the Release mode -#endif // _MSC_VER > 1000 - - -#include "zipstring.h" -#include "zipbaseexception.h" -#include "ZipExport.h" - -#define ZIP_ENABLE_ERROR_DESCRIPTION - -/** - A class representing exceptions specific to the ZipArchive library. - Library exception class derived in the MFC version from \c CException - and in non-MFC version from \c std::exception. -*/ -class ZIP_API CZipException : public CZipBaseException -{ -public: - -/** - \param iCause - error cause (takes one of the #ZipErrors enumeration codes) - \param lpszZipName - the name of the file where the error occurred (if applicable) -*/ - CZipException(int iCause = generic, LPCTSTR lpszZipName = NULL); - - CZipException(CZipException& e) - { - m_szFileName = e.m_szFileName; - m_iCause = e.m_iCause; - } - -/** - Throw an exception. - Throw CZipException* in the MFC version of the library - (the object must be deleted with Delete() method) - and CZipException in other versions. - - The arguments are the same as in CZipException(). - - \param iZipError - \param lpszZipName - - \see CZipException() - -*/ - - static void Throw(int iZipError = CZipException::generic, LPCTSTR lpszZipName = NULL) - { - #ifdef _MFC_VER - throw new CZipException(iZipError, lpszZipName); - #else - CZipException e(iZipError, lpszZipName); - throw e; - #endif - } - - -/** - Convert a zlib library error code to a \link #ZipErrors CZipException error code \endlink - \param iZlibError - zlib library error code - \return \link #ZipErrors CZipException error code \endlink -*/ - - static int ZlibErrToZip(int iZlibError); - - -#ifdef ZIP_ENABLE_ERROR_DESCRIPTION - - /** - Return the error description. - \note You need to have defined ZIP_ENABLE_ERROR_DESCRIPTION - (in file ZipException.h); undefine this value if you don't want to - store the messages in the library. - - - */ - CZipString GetErrorDescription(); - - - /** - Return the description of the error based on system variables - (this function is provided only for compatibility with MFC \c CException::GetErrorMessage) - - \param lpszError - a pointer to a buffer that will receive the error message - if \c NULL - - \param nMaxError - the maximum number of characters the buffer can hold, including the NULL terminator - - - \return - \c TRUE if the error string is not empty - \note - - The function will not copy more than \c nMaxError – 1 characters - to the buffer, and it always adds a trailing null to end the string; - if the buffer is too small, the error message will be truncated. - - You need to have defined ZIP_ENABLE_ERROR_DESCRIPTION - (in file ZipException.h); undefine this value if you don't want to - store the messages in the library. - - */ - BOOL GetErrorMessage(LPTSTR lpszError, UINT nMaxError, UINT* = NULL); - -#endif //ZIP_ENABLE_ERROR_DESCRIPTION - - /** - The name of the zip file where the error occurred. - */ - CZipString m_szFileName; - - /** - The codes of errors thrown by the ZipArchive library - */ - enum ZipErrors - { - noError, ///< no error -// 1 - 42 reserved for errno (from STL) values - used only in non-MFC versions -// 43 - 99 reserved - generic = 100, ///< unknown error - badZipFile, ///< damaged or not a zip file - badCrc, ///< crc mismatched - noCallback, ///< no disk-spanning callback functor set - aborted, ///< callback functor's method Callback returned \c false while disk change in the disk-spanning archive - abortedAction, ///< callback functor's method Callback returned \c false in CZipArchive class members: AddNewFile, ExtractFile, TestFile, DeleteFile or DeleteFiles - abortedSafely, ///< the same as above, you may be sure that the operation was successfully completed before or it didn't cause any damage in the archive (break when counting before deleting files; see CZipArchive::cbDeleteCnt) - nonRemovable, ///< the disk selected for pkzipSpan archive is non removable - tooManyVolumes, ///< limit of the maximum volumes reached (999) - tooLongFileName, ///< the filename of the file added to the archive is too long - badPassword, ///< incorrect password set for the file being decrypted - dirWithSize, ///< during testing: found the directory with the size greater than 0 - internal, ///< internal error - notRemoved, ///< error while removing a file (under Windows call GetLastError() to find out more) - notRenamed, ///< error while renaming a file (under Windows call GetLastError() to find out more) - platfNotSupp, ///< the platform that the zip file is being created for is not supported - cdirNotFound, ///< the central directory was not found in the archive (it is thrown also when the last disk of multi-disk archive is not in the drive when opening the archive) - streamEnd = 500, ///< zlib library error - needDict, ///< zlib library error - errNo, ///< zlib library error - streamError, ///< zlib library error - dataError, ///< zlib library error - memError, ///< zlib library error thrown by CZipMemFile as well - bufError, ///< zlib library error - versionError, ///< zlib library error - }; - - - - /** - A cause of the error - takes one of the #ZipErrors enumeration codes. - */ - int m_iCause; - -#if __GNUC__ >=3 - virtual ~CZipException() throw(); -#else - virtual ~CZipException(); -#endif -protected: - -#ifdef ZIP_ENABLE_ERROR_DESCRIPTION - - - /** - Return the error description - - \param iCause : error number - \param bNoLoop: if \c true tells not to search for en error description, - it the error is generic - - \return - */ - CZipString GetInternalErrorDescription(int iCause, bool bNoLoop = false); - - - /** - Return the description of the error based on system variables - - - \return - */ - CZipString GetSystemErrorDescription(); - - -#endif //ZIP_ENABLE_ERROR_DESCRIPTION - -#ifdef _MFC_VER - DECLARE_DYNAMIC(CZipException) - #pragma warning( pop ) -#endif -}; - - -#endif // !defined(AFX_ZIPEXCEPTION_H__E3546921_D728_11D3_B7C7_E77339672847__INCLUDED_) - - diff --git a/harbour/contrib/hbziparch/zipfile.cpp b/harbour/contrib/hbziparch/zipfile.cpp deleted file mode 100644 index 3e76774798..0000000000 --- a/harbour/contrib/hbziparch/zipfile.cpp +++ /dev/null @@ -1,116 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipFile.cpp $ -// $Archive: /ZipArchive_STL/ZipFile.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#include "stdafx.h" -#include "zipfile.h" -#include "zipexception.h" -#include "zipplatform.h" - -#include - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -CZipFile::CZipFile() -{ - m_hFile = -1; -} - - - - -void CZipFile::ThrowError() const -{ - CZipException::Throw(errno, m_szFileName); -} - - -ZIP_ULONGLONG CZipFile::GetLength() const -{ -// cannot use Seek here, Seek is not const - long lLen, lCur; - lCur = lseek(m_hFile, 0, current); - if (lCur == -1) - ThrowError(); - lLen = lseek(m_hFile, 0, end); - // first get back - lseek(m_hFile, lCur, begin); - if (lLen == -1) - ThrowError(); - return lLen; - -} - - -bool CZipFile::Open(LPCTSTR lpszFileName, UINT openFlags, bool bThrow) -{ - if (!IsClosed()) - Close(); -#ifndef __GNUC__ - UINT iNewFlags = O_BINARY; -#else - UINT iNewFlags = 0; -#endif - bool bReadOnly = false; - if (openFlags & CZipFile::modeCreate) - iNewFlags |= O_CREAT; - if ((openFlags & CZipFile::modeReadWrite) == CZipFile::modeReadWrite) - iNewFlags |= O_RDWR; - else if (openFlags & CZipFile::modeRead) - { - // O_RDONLY is defined as 0 - bReadOnly = true; - iNewFlags |= O_RDONLY; - } - else if (openFlags & CZipFile::modeWrite) - iNewFlags |= O_WRONLY; - - if (!(openFlags & CZipFile::modeNoTruncate) && !bReadOnly) - iNewFlags |= O_TRUNC; - - m_hFile = ZipPlatform::OpenFile(lpszFileName, iNewFlags, openFlags & 0x1C); - if (m_hFile == -1) - { - if (bThrow) - ThrowError(); - else - return false; - } - m_szFileName = lpszFileName; - return true; -} - - -void CZipFile::SetLength(ZIP_ULONGLONG nNewLen) -{ - ZipPlatform::TruncateFile(m_hFile, (DWORD)nNewLen); -} - - -void CZipFile::Flush() -{ - if (!ZipPlatform::FlushFile(m_hFile)) - ThrowError(); -} - -CZipFile::operator HANDLE() -{ - int fh = ZipPlatform::GetFileSystemHandle(m_hFile); - if (fh == -1) - ThrowError(); - return (HANDLE)fh; -} diff --git a/harbour/contrib/hbziparch/zipfile.h b/harbour/contrib/hbziparch/zipfile.h deleted file mode 100644 index e44c8e9240..0000000000 --- a/harbour/contrib/hbziparch/zipfile.h +++ /dev/null @@ -1,116 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipFile.h $ -// $Archive: /ZipArchive_STL/ZipFile.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_) -#define AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "zipabstractfile.h" -#include "zipstring.h" -#include "ZipExport.h" - -#ifndef __GNUC__ - #include -#else - #include - #include -#endif - -class ZIP_API CZipFile :public CZipAbstractFile -{ - void ThrowError() const; -public: - int m_hFile; - operator HANDLE(); - enum OpenModes - { - modeRead = 0x0001, - modeWrite = 0x0002, - modeReadWrite = modeRead | modeWrite, - shareDenyWrite = 0x0004, - shareDenyRead = 0x0008, - shareDenyNone = 0x0010, - modeCreate = 0x0020, - modeNoTruncate = 0x0040, - }; - - CZipFile(LPCTSTR lpszFileName, UINT openFlags) - { - m_hFile = -1; - Open(lpszFileName, openFlags, true); - } - void Flush(); - ZIP_ULONGLONG GetLength() const; - CZipString GetFilePath() const {return m_szFileName;} - bool IsClosed()const { return m_hFile == -1;} - bool Open(LPCTSTR lpszFileName, UINT openFlags, bool bThrow); - void Close() - { - if (IsClosed()) - return; - - if (close(m_hFile) != 0) - ThrowError(); - else - { - m_szFileName.empty(); - m_hFile = -1; - } - } - void Write(const void* lpBuf, UINT nCount) - { - if (write(m_hFile, lpBuf, nCount) != (int) nCount) - ThrowError(); - } - ZIP_ULONGLONG GetPosition() const - { -#ifndef __GNUC__ - long ret = tell(m_hFile); -#else - long ret = lseek(m_hFile, 0, SEEK_CUR); -#endif - if (ret == -1L) - ThrowError(); - return ret; - } - void SetLength(ZIP_ULONGLONG nNewLen); - UINT Read(void *lpBuf, UINT nCount) - { - errno = 0; - int ret = read(m_hFile, lpBuf, nCount); - if (ret < (int) nCount && errno != 0) - ThrowError(); - return ret; - - } - ZIP_ULONGLONG Seek(ZIP_LONGLONG dOff, int nFrom) - { - long ret = lseek(m_hFile, (long)dOff, nFrom); - if (ret == -1) - ThrowError(); - return ret; - } - CZipFile (); - virtual ~CZipFile (){Close();}; -protected: - CZipString m_szFileName; - -}; - -#endif // !defined(AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipfileheader.cpp b/harbour/contrib/hbziparch/zipfileheader.cpp deleted file mode 100644 index fb810f8784..0000000000 --- a/harbour/contrib/hbziparch/zipfileheader.cpp +++ /dev/null @@ -1,340 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipFileHeader.cpp $ -// $Archive: /ZipArchive_STL/ZipFileHeader.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" -#include "zipfileheader.h" -#include "zipautobuffer.h" -#include "ziparchive.h" -#include "zipplatform.h" -#include "zipcompatibility.h" -#include - -#define FILEHEADERSIZE 46 -#define LOCALFILEHEADERSIZE 30 - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// -char CZipFileHeader::m_gszSignature[] = {0x50, 0x4b, 0x01, 0x02}; -char CZipFileHeader::m_gszLocalSignature[] = {0x50, 0x4b, 0x03, 0x04}; -CZipFileHeader::CZipFileHeader() -{ - m_uExternalAttr = 0;//ZipPlatform::GetDefaultAttributes(); - m_uModDate = m_uModTime = 0; - m_uMethod = Z_DEFLATED; -// SetSystemCompatibility(ZipPlatform::m_sSystemID); -} - -CZipFileHeader::~CZipFileHeader() -{ - -} - -// read the header from the central dir -bool CZipFileHeader::Read(CZipStorage *pStorage) -{ -// // just in case -// m_pszComment.Release(); -// m_pszFileName.Release(); - WORD uFileNameSize, uCommentSize, uExtraFieldSize; - CZipAutoBuffer buf(FILEHEADERSIZE); - pStorage->Read(buf, FILEHEADERSIZE, true); - memcpy(&m_szSignature, buf, 4); - memcpy(&m_uVersionMadeBy, buf + 4, 2); - memcpy(&m_uVersionNeeded, buf + 6, 2); - memcpy(&m_uFlag, buf + 8, 2); - memcpy(&m_uMethod, buf + 10, 2); - memcpy(&m_uModTime, buf + 12, 2); - memcpy(&m_uModDate, buf + 14, 2); - memcpy(&m_uCrc32, buf + 16, 4); - memcpy(&m_uComprSize, buf + 20, 4); - memcpy(&m_uUncomprSize, buf + 24, 4); - memcpy(&uFileNameSize, buf + 28, 2); - memcpy(&uExtraFieldSize, buf + 30, 2); - memcpy(&uCommentSize, buf + 32, 2); - memcpy(&m_uDiskStart, buf + 34, 2); - memcpy(&m_uInternalAttr, buf + 36, 2); - memcpy(&m_uExternalAttr, buf + 38, 4); - memcpy(&m_uOffset, buf + 42, 4); - buf.Release(); - - if (memcmp(m_szSignature, m_gszSignature, 4) != 0) - return false; - - int iCurDsk = pStorage->GetCurrentDisk(); - m_pszFileName.Allocate(uFileNameSize); // don't add NULL at the end - pStorage->Read(m_pszFileName, uFileNameSize, true); - if (uExtraFieldSize) - { - ASSERT(!m_pExtraField.IsAllocated()); - m_pExtraField.Allocate(uExtraFieldSize); - pStorage->Read(m_pExtraField, uExtraFieldSize, true); - } - if (uCommentSize) - { - m_pszComment.Allocate(uCommentSize); - pStorage->Read(m_pszComment, uCommentSize, true); - } - - return pStorage->GetCurrentDisk() == iCurDsk; // check that the whole header is on the one disk -} - -time_t CZipFileHeader::GetTime()const -{ - struct tm atm; - atm.tm_sec = (m_uModTime & ~0xFFE0) << 1; - atm.tm_min = (m_uModTime & ~0xF800) >> 5; - atm.tm_hour = m_uModTime >> 11; - - atm.tm_mday = m_uModDate & ~0xFFE0; - atm.tm_mon = ((m_uModDate & ~0xFE00) >> 5) - 1; - atm.tm_year = (m_uModDate >> 9) + 80; - atm.tm_isdst = -1; - return mktime(&atm); -} - -// write the header to the central dir -DWORD CZipFileHeader::Write(CZipStorage *pStorage) -{ - WORD uFileNameSize = GetFileNameSize(), uCommentSize = GetCommentSize(), - uExtraFieldSize = GetExtraFieldSize(); - DWORD iSize = FILEHEADERSIZE + uFileNameSize + uCommentSize + uExtraFieldSize; - CZipAutoBuffer buf(iSize); - memcpy(buf, &m_szSignature, 4); - memcpy(buf + 4, &m_uVersionMadeBy, 2); - memcpy(buf + 6, &m_uVersionNeeded, 2); - memcpy(buf + 8, &m_uFlag, 2); - memcpy(buf + 10, &m_uMethod, 2); - memcpy(buf + 12, &m_uModTime, 2); - memcpy(buf + 14, &m_uModDate, 2); - memcpy(buf + 16, &m_uCrc32, 4); - memcpy(buf + 20, &m_uComprSize, 4); - memcpy(buf + 24, &m_uUncomprSize, 4); - memcpy(buf + 28, &uFileNameSize, 2); - memcpy(buf + 30, &uExtraFieldSize, 2); - memcpy(buf + 32, &uCommentSize, 2); - memcpy(buf + 34, &m_uDiskStart, 2); - memcpy(buf + 36, &m_uInternalAttr, 2); - memcpy(buf + 38, &m_uExternalAttr, 4); - memcpy(buf + 42, &m_uOffset, 4); - - memcpy(buf + 46, m_pszFileName, uFileNameSize); - - if (uExtraFieldSize) - memcpy(buf + 46 + uFileNameSize, m_pExtraField, uExtraFieldSize); - - if (uCommentSize) - memcpy(buf + 46 + uFileNameSize + uExtraFieldSize, m_pszComment, uCommentSize); - - pStorage->Write(buf, iSize, true); - return iSize; -} - -bool CZipFileHeader::ReadLocal(CZipStorage *pStorage, WORD& iLocExtrFieldSize) -{ - char buf[LOCALFILEHEADERSIZE]; - pStorage->Read(buf, LOCALFILEHEADERSIZE, true); - if (memcmp(buf, m_gszLocalSignature, 4) != 0) - return false; - - bool bIsDataDescr = (((WORD)*(buf + 6)) & 8) != 0; - - WORD uFileNameSize = GetFileNameSize(); - WORD uTemp; - memcpy(&uTemp, buf+6, 2); // give the priority to the local flag - if ((uTemp & 0xf) != (m_uFlag & 0xf)) - m_uFlag = uTemp; - if ((memcmp(buf + 8, &m_uMethod, 2) != 0) - || (m_uMethod && (m_uMethod != Z_DEFLATED)) - || (memcmp(buf + 26, &uFileNameSize, 2) != 0)) - return false; - -// jeszcze mo¿naby porównaæ nazwy plików - - if (!bIsDataDescr/* || !pStorage->IsSpanMode()*/) - if (!CheckCrcAndSizes(buf + 14)) - return false; - - memcpy(&iLocExtrFieldSize, buf + 28, 2); - pStorage->m_pFile->Seek(uFileNameSize, CZipAbstractFile::current); - - return true; -} - -void CZipFileHeader::SetTime(const time_t & ttime) -{ - tm* gt = localtime(&ttime); - WORD year = (WORD)(gt->tm_year + 1900); - if (year <= 1980) - year = 0; - else - year -= 1980; - m_uModDate = (WORD) (gt->tm_mday + ((gt->tm_mon + 1)<< 5) + (year << 9)); - m_uModTime = (WORD) ((gt->tm_sec >> 1) + (gt->tm_min << 5) + - (gt->tm_hour << 11)); -} -// the buffer contains crc32, compressed and uncompressed sizes to be compared -// with the actual values -bool CZipFileHeader::CheckCrcAndSizes(char *pBuf) const -{ - return (memcmp(pBuf, &m_uCrc32, 4) == 0) && (memcmp(pBuf + 4, &m_uComprSize, 4) == 0) - && (memcmp(pBuf + 8, &m_uUncomprSize, 4) == 0); -} - -// write the local header -void CZipFileHeader::WriteLocal(CZipStorage& storage) -{ - // extra field is local by now - WORD uFileNameSize = GetFileNameSize(), uExtraFieldSize = GetExtraFieldSize(); - DWORD iLocalSize = LOCALFILEHEADERSIZE + uExtraFieldSize + uFileNameSize; - CZipAutoBuffer buf(iLocalSize); - memcpy(buf, m_gszLocalSignature, 4); - memcpy(buf + 4, &m_uVersionNeeded, 2); - memcpy(buf + 6, &m_uFlag, 2); - memcpy(buf + 8, &m_uMethod, 2); - memcpy(buf + 10, &m_uModTime, 2); - memcpy(buf + 12, &m_uModDate, 2); - memcpy(buf + 14, &m_uCrc32, 4); - memcpy(buf + 18, &m_uComprSize, 4); - memcpy(buf + 22, &m_uUncomprSize, 4); - memcpy(buf + 26, &uFileNameSize, 2); - memcpy(buf + 28, &uExtraFieldSize, 2); - memcpy(buf + 30, m_pszFileName, uFileNameSize); - memcpy(buf + 30 + uFileNameSize, m_pExtraField, uExtraFieldSize); - - // possible disk change before writing to the file in the disk spanning mode - // so write the local header first - storage.Write(buf, iLocalSize, true); - // it was only local information, use CZipArchive::SetExtraField to set the file extra field in the central directory - m_pExtraField.Release(); - - m_uDiskStart = (WORD)storage.GetCurrentDisk(); - m_uOffset = storage.GetPosition() - iLocalSize; -} - -// prepare the data before adding a new file -bool CZipFileHeader::PrepareData(int iLevel, bool bSpan, bool bEncrypted) -{ - memcpy(m_szSignature, m_gszSignature, 4); - m_uInternalAttr = 0; - m_uVersionNeeded = IsDirectory() ? 0xa : 0x14; // 1.0 or 2.0 - SetVersion((WORD)(0x14)); - - m_uCrc32 = 0; - m_uComprSize = 0; - m_uUncomprSize = 0; - if (iLevel == 0) - m_uMethod = 0; - - if ((m_uMethod != Z_DEFLATED) && (m_uMethod != 0)) - m_uMethod = Z_DEFLATED; - - m_uFlag = 0; - if (m_uMethod == Z_DEFLATED) - switch (iLevel) - { - case 1: - m_uFlag |= 6; - break; - case 2: - m_uFlag |= 4; - break; - case 8: - case 9: - m_uFlag |= 2; - break; - } - - if (bSpan || bEncrypted) - m_uFlag |= 8; // data descriptor present - - if (bEncrypted) - { - m_uComprSize = ZIPARCHIVE_ENCR_HEADER_LEN; // encrypted header - m_uFlag |= 1; // encrypted file - } - - return !(m_pszComment.GetSize() > USHRT_MAX || m_pszFileName.GetSize() > USHRT_MAX - || m_pExtraField.GetSize() > USHRT_MAX); -} - -void CZipFileHeader::GetCrcAndSizes(char * pBuffer)const -{ - memcpy(pBuffer, &m_uCrc32, 4); - memcpy(pBuffer + 4, &m_uComprSize, 4); - memcpy(pBuffer + 8, &m_uUncomprSize, 4); -} - -DWORD CZipFileHeader::GetSize(bool bLocal)const -{ - if (bLocal) - return LOCALFILEHEADERSIZE + GetExtraFieldSize() + GetFileNameSize(); - else - return FILEHEADERSIZE + GetExtraFieldSize() + GetFileNameSize() + GetCommentSize(); -} - - -bool CZipFileHeader::SetComment(LPCTSTR lpszComment) -{ - return CZipArchive::WideToSingle(lpszComment, m_pszComment) != -1; -} - -CZipString CZipFileHeader::GetComment() const -{ - CZipString temp; - CZipArchive::SingleToWide(m_pszComment, temp); - return temp; - -} - -bool CZipFileHeader::SetFileName(LPCTSTR lpszFileName) -{ - - return CZipArchive::WideToSingle(lpszFileName, m_pszFileName) != -1; -} - -CZipString CZipFileHeader::GetFileName()const -{ - CZipString temp; - CZipArchive::SingleToWide(m_pszFileName, temp); - return temp; -} - -bool CZipFileHeader::IsDirectory()const -{ - return ZipPlatform::IsDirectory(GetSystemAttr()); -} - -DWORD CZipFileHeader::GetSystemAttr()const -{ - int iSystemComp = GetSystemCompatibility(); - if (ZipCompatibility::IsPlatformSupported(iSystemComp)) - { - if (!m_uExternalAttr && CZipPathComponent::HasEndingSeparator(GetFileName())) - return ZipPlatform::GetDefaultDirAttributes(); // can happen - else - return ZipCompatibility::ConvertToSystem(m_uExternalAttr, iSystemComp, ZipPlatform::GetSystemID()); - } - else - return CZipPathComponent::HasEndingSeparator(GetFileName()) ? ZipPlatform::GetDefaultDirAttributes() : ZipPlatform::GetDefaultAttributes(); -} - - -void CZipFileHeader::SetSystemAttr(DWORD uAttr) -{ - m_uExternalAttr = ZipCompatibility::ConvertToSystem(uAttr, ZipPlatform::GetSystemID(), GetSystemCompatibility()); -} diff --git a/harbour/contrib/hbziparch/zipfileheader.h b/harbour/contrib/hbziparch/zipfileheader.h deleted file mode 100644 index b1b0eac8ac..0000000000 --- a/harbour/contrib/hbziparch/zipfileheader.h +++ /dev/null @@ -1,352 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipFileHeader.h $ -// $Archive: /ZipArchive/ZipFileHeader.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipFileHeader.h -* Interface for the CZipFileHeader class. -* -*/ - -#if !defined(AFX_FILEHEADER_H__0081FC65_C9C9_4D48_AF72_DBF37DF5E0CF__INCLUDED_) -#define AFX_FILEHEADER_H__0081FC65_C9C9_4D48_AF72_DBF37DF5E0CF__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "ZipExport.h" -#include "zipstorage.h" -#include "zipautobuffer.h" -#include "sys/types.h" -#include "zipcompatibility.h" -#define ZIPARCHIVE_ENCR_HEADER_LEN 12 - -/** - Representation of a single file stored in the zip archive. - Modify all the class attributes BEFORE adding a file to and archive - ( using CZipArchive::OpenNewFile ). - It is not possible to modify the data of the existing files in the archive - (it would mean updating all the information in the local headers - and the offsets would be changed as well when the filename would changed its size) -*/ -class ZIP_API CZipFileHeader -{ - friend class CZipCentralDir; - friend class CZipArchive; - friend void ZipCompatibility::FileNameUpdate(CZipFileHeader&, bool); -public: - CZipFileHeader(); - virtual ~CZipFileHeader(); - - -// -/** - Change slash to backslash or vice-versa in #m_pszFileName. - \param bWindowsStyle - if \c true, change slash to backslash; otherwise vice versa; -*/ - -/** - \return the filename size in characters (without NULL) -*/ - WORD GetFileNameSize()const {return (WORD)m_pszFileName.GetSize();} - -/** - \return the comment size in characters (without NULL) -*/ - WORD GetCommentSize() const {return (WORD)m_pszComment.GetSize();} - -/** - \return the extra field size in characters -*/ - WORD GetExtraFieldSize()const{return (WORD)m_pExtraField.GetSize();} - -/** - \return the filename -*/ - CZipString GetFileName()const; - -/** - Set the filename - \param lpszFileName - - \return - \c true, if conversion from UNICODE to single byte was successful - (or if there was no conversion needed or possible); otherwise \c false; -*/ - bool SetFileName(LPCTSTR lpszFileName); - -/** - \return the file comment -*/ - CZipString GetComment() const; - -/** - Set the file comment. - \param lpszComment - - \return - \c true, if conversion from UNICODE to single byte was successful - (or if there was no conversion needed or possible); otherwise \c false; - -*/ - bool SetComment(LPCTSTR lpszComment); - -/** - \return \c true if the data descriptor is present -*/ - bool IsDataDescr()const { return ((m_uFlag & 8) != 0); } - - - /** - \return - get the effective compressed size: if the file is encrypted, return less by the size of the encryption header - */ - DWORD GetEffComprSize() - { - return m_uComprSize - (IsEncrypted() ? ZIPARCHIVE_ENCR_HEADER_LEN : 0); - } - /** - \return - \c false if the file should be stored instead of being compressed - */ - bool CompressionEfficient() - { - DWORD uBefore = m_uUncomprSize; - // ignore the length of encryption header - DWORD uAfter = GetEffComprSize(); - return uAfter <= uBefore; - } - - /** - \return the compression ratio of the file - */ - float GetCompressionRatio() - { - return m_uUncomprSize ? ((float)m_uComprSize) * 100 / m_uUncomprSize : 0; - } - -/** - \return \c if the file is encrypted ( a password is needed to extract this file) - \see CZipArchive::SetPassword -*/ - bool IsEncrypted()const { return ((m_uFlag & 1) != 0); } - - char m_szSignature[4]; ///< central file header signature - WORD m_uVersionMadeBy; ///< version made by and system compatibility - WORD m_uVersionNeeded; ///< version needed to extract - WORD m_uFlag; ///< general purpose bit flag - WORD m_uMethod; ///< compression method - WORD m_uModTime; ///< last mod file time - WORD m_uModDate; ///< last mod file date - DWORD m_uCrc32; ///< crc-32 - DWORD m_uComprSize; ///< compressed size - DWORD m_uUncomprSize; ///< uncompressed size -// filename length 2 bytes -// WORD m_uFileNameSize; -// extra field length 2 bytes -// WORD m_uExtraFieldSize; -// file comment length 2 bytes -// WORD m_uCommentSize; - WORD m_uDiskStart; ///< disk number start - WORD m_uInternalAttr; ///< internal file attributes -protected: - DWORD m_uExternalAttr; ///< external file attributes -public: - DWORD m_uOffset; ///< relative offset of local header - CZipAutoBuffer m_pExtraField; ///< extra field (variable size) - static char m_gszSignature[]; ///< central file header signature - static char m_gszLocalSignature[]; ///< local file header signature - - -/** - Set #m_uModDate, #m_uModTime - (file modification time) - \param ttime - \see GetTime -*/ - void SetTime(const time_t& ttime); - -/** - \return the modification time - \see SetTime -*/ - time_t GetTime()const; - -/** - \param bLocal - if \c true return the local file header size or in the central directory otherwise - \return the total size of the structure depending on the \e bLocal parameter -*/ - DWORD GetSize(bool bLocal = false)const; - -/** - \return the system compatibility of the current file as - the one of ZipCompatibility::ZipPlatforms values; - usually the same as CZipArchive::GetSystemComatibility. - Software can use this information e.g. to determine the line - record format for text files etc. - ZipArchive library uses it to perform a proper attributes conversion. - - \see CZipArchive::GetSystemComatibility - \see ZipPlatform::GetSystemID -*/ - int GetSystemCompatibility()const - { - return (m_uVersionMadeBy & 0xFF00) >> 8; - } - -/** - \return the attributes of the file converted to the current system compatible value - \note - - Throws exception if the archive system or the current system - is not supported by the ZipArchive library. - - (only Linux version): After obtaining the attributes, you need to shift them right by 16 -*/ - - DWORD GetSystemAttr()const; - - /** - \return - the original attributes as stored in the archive (without performing any conversion) - */ - DWORD GetOriginalAttributes() const {return m_uExternalAttr;} - -/** - \return \c true, if this object represents a directory; otherwise \c false; - If #m_uExternalAttr value is zero, the function check for a presence of a path - separator at the end of the file name. If it is present, it is assumed to be a directory. -*/ - bool IsDirectory()const; - - -protected: - -/** - Set the system compatibility of the file. - \param iSystemID - one of ZipCompatibility::ZipPlatforms values - \see CZipArchive::GetSystemCompatibility -*/ - void SetSystemCompatibility(int iSystemID) - { - m_uVersionMadeBy &= 0x00FF; - m_uVersionMadeBy |= (WORD)(iSystemID << 8); - } - -/** - Set the system attributes - if you wish to set the attributes of this structure use CZipArchive::SetFileHeaderAttr() - \param uAttr - attributes to set - \note Throws exceptions if the archive system or the current system - is not supported by the ZipArchive library. - \see CZipArchive::SetFileHeaderAttr - \see GetSystemAttr - \see SetSystemCompatibility -*/ - void SetSystemAttr(DWORD uAttr); - -/** - Set the version made by number. - -*/ - void SetVersion(WORD uVersion) - { - if ((m_uVersionMadeBy & 0x00FF) != (uVersion & 0x00FF)) - { - m_uVersionMadeBy &= 0xFF00; - m_uVersionMadeBy |= (WORD)(uVersion & 0x00FF); - } - } - - /** - a filename - */ - CZipAutoBuffer m_pszFileName; - - /** - a file comment - */ - CZipAutoBuffer m_pszComment; - -/** - Fill the buffer with the current values of crc and compressed and - uncompressed sizes of the file. - - -*/ - void GetCrcAndSizes(char* pBuffer)const; - -/** - Check whether the actual values of crc and compressed and - uncompressed sizes of the file are the same as defined in - the file header. - \param pBuf - buffer with the mentioned data - \return \c true if they are the same; otherwise \c false; -*/ - bool CheckCrcAndSizes(char* pBuf) const; - - -/** - Prepare the data for the class while adding a new file. - Called by CZipArchive::OpenNewFile - \param iLevel - a compression level - \param bSpan - \c true, if the data descriptor will be present because of spanning archive - \param bEncrypted - \c true, if the file will be encrypted - \return \c true if the sizes of the filename, extra field and comments - does not exceed \c unsigned \c short maximum value; otherwise \c false; -*/ - bool PrepareData(int iLevel, bool bSpan, bool bEncrypted); -/** - Write the local file header to the \e storage - \param storage - \note Throws exceptions. -*/ - void WriteLocal(CZipStorage& storage); - -/** - Read the file header from the central directory record from \e pStorage. - \param *pStorage - \return \c true if the whole file header is on one disk in - a multi-disk archive; otherwise \c false; - \note Throws exceptions. -*/ - bool Read(CZipStorage *pStorage); -/** - Read the local file header from \e pStorage and check for consistency. - \param *pStorage - \param iLocExtrFieldSize - receives local extra field size - \return \c false, if something goes wrong; otherwise \c true; - \note Throws exceptions. -*/ - bool ReadLocal(CZipStorage *pStorage, WORD& iLocExtrFieldSize); -/** - Write the file header to \e pStorage. - \param *pStorage - \return the size of the file header - \note Throws exceptions. -*/ - DWORD Write(CZipStorage *pStorage); - -}; - -#endif // !defined(AFX_FILEHEADER_H__0081FC65_C9C9_4D48_AF72_DBF37DF5E0CF__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipfilemapping.h b/harbour/contrib/hbziparch/zipfilemapping.h deleted file mode 100644 index da271c93d6..0000000000 --- a/harbour/contrib/hbziparch/zipfilemapping.h +++ /dev/null @@ -1,132 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipFileMapping.h $ -// $Archive: /ZipArchive/ZipFileMapping.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -// -// Check the site http://www.artpol-software.com for the updated version of the library. -//////////////////////////////////////////////////////////////////////////////// - -#include "hbapi.h" - -#if !defined(AFX_AUTOHANDLE_H__D68326EA_D7FA_4792_AB1F_68D09533E399__INCLUDED_) -#define AFX_AUTOHANDLE_H__D68326EA_D7FA_4792_AB1F_68D09533E399__INCLUDED_ - -#ifdef HB_OS_LINUX - -#include - -namespace ziparchv -{ - - - struct CZipFileMapping - { - CZipFileMapping() - { - m_iSize = 0; - m_pFileMap = NULL; - } - bool CreateMapping(CZipFile* pFile) - { - if (!pFile) - return false; - m_iSize = pFile->GetLength(); - m_pFileMap = mmap(0, m_iSize, PROT_READ|PROT_WRITE, MAP_SHARED, pFile->m_hFile, 0); - return (m_pFileMap != NULL); - } - void RemoveMapping() - { - - if (m_pFileMap) - { - munmap(m_pFileMap, m_iSize); - m_pFileMap = NULL; - } - } - ~CZipFileMapping() - { - RemoveMapping(); - } - char* GetMappedMemory() - { - return reinterpret_cast (m_pFileMap); - } - protected: - void* m_pFileMap; - size_t m_iSize; - - }; -} - -#else /* HB_OS_LINUX */ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "zipfile.h" -namespace ziparchv -{ - - - struct CZipFileMapping - { - CZipFileMapping() - { - m_hFileMap = NULL; - m_pFileMap = NULL; - } - bool CreateMapping(CZipFile* pFile) - { - if (!pFile) - return false; - m_hFileMap = CreateFileMapping((*pFile), NULL, PAGE_READWRITE, - 0, 0, _T("ZipArchive Mapping File")); - if (!m_hFileMap) - return false; - // Get pointer to memory representing file - m_pFileMap = MapViewOfFile(m_hFileMap, FILE_MAP_WRITE, 0, 0, 0); - return (m_pFileMap != NULL); - } - void RemoveMapping() - { - if (m_pFileMap) - { - UnmapViewOfFile(m_pFileMap); - m_pFileMap = NULL; - } - if (m_hFileMap) - { - CloseHandle(m_hFileMap); - m_hFileMap = NULL; - } - - } - ~CZipFileMapping() - { - RemoveMapping(); - } - char* GetMappedMemory() - { - return reinterpret_cast (m_pFileMap); - } - protected: - HANDLE m_hFileMap; - LPVOID m_pFileMap; - - }; -} - -#endif /* HB_OS_LINUX */ - -#endif // !defined(AFX_AUTOHANDLE_H__D68326EA_D7FA_4792_AB1F_68D09533E399__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipinternalinfo.h b/harbour/contrib/hbziparch/zipinternalinfo.h deleted file mode 100644 index e719afe81e..0000000000 --- a/harbour/contrib/hbziparch/zipinternalinfo.h +++ /dev/null @@ -1,60 +0,0 @@ -/** -* \file ZipInternalInfo.h -* Interface for the CZipInternalInfo structure. -* -* \author Tadeusz Dracz -*/ -// Part of the ZipArchive library -// -// Copyright (C) 2000 - 2001 Tadeusz Dracz. -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_ZIPINTERNALINFO_H__C6749101_590C_4F74_8121_B82E3BE9FA44__INCLUDED_) -#define AFX_ZIPINTERNALINFO_H__C6749101_590C_4F74_8121_B82E3BE9FA44__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -#include "zipautobuffer.h" -#include "hbzlib.h" - -/** - The purpose of this structure is to hold the data that allow communication - with the zlib library -*/ -ZEXPORT struct CZipInternalInfo -{ - CZipInternalInfo(); - virtual ~CZipInternalInfo(); - -/** - Allocate internal buffer of m_iBufferSize size -*/ - void Init(); - z_stream m_stream; ///< zlib library data stream - DWORD m_uUncomprLeft; ///< bytes left to uncompress - DWORD m_uComprLeft; ///< bytes left to decompress - DWORD m_uCrc32; ///< crc32 file control value - - /** - The size of the buffer used in decompressing data. - Set before opening the archive. - It is usually set with CZipArchive::SetAdvanced - (specify this value as the second argument). - \see CZipArchive::SetAdvanced - */ - DWORD m_iBufferSize; - - /** - This buffer caches data during compression and decompression. - */ - CZipAutoBuffer m_pBuffer; -}; - -#endif // !defined(AFX_ZIPINTERNALINFO_H__C6749101_590C_4F74_8121_B82E3BE9FA44__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipmemfile.cpp b/harbour/contrib/hbziparch/zipmemfile.cpp deleted file mode 100644 index a25fb3f7ba..0000000000 --- a/harbour/contrib/hbziparch/zipmemfile.cpp +++ /dev/null @@ -1,98 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipMemFile.cpp $ -// $Archive: /ZipArchive/ZipMemFile.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#include "stdafx.h" -#include "zipmemfile.h" -#include "zipexception.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -void CZipMemFile::Grow(size_t nGrowTo) -{ - if (m_nBufSize < (UINT)nGrowTo) - { - if (m_nGrowBy == 0) - CZipException::Throw(CZipException::memError); - size_t nNewSize = m_nBufSize; - while (nNewSize < nGrowTo) - nNewSize += m_nGrowBy; - BYTE* lpNew; - if (m_lpBuf) - lpNew = (BYTE*)hb_xrealloc((void*) m_lpBuf, nNewSize); - else - lpNew = (BYTE*)hb_xalloc(nNewSize); - - if (!lpNew) - CZipException::Throw(CZipException::memError); - m_nBufSize = nNewSize; - m_lpBuf = lpNew; - } -} - -void CZipMemFile::SetLength(ZIP_ULONGLONG nNewLen) -{ - if (m_nBufSize < (UINT)nNewLen) - Grow((size_t)nNewLen); - else - m_nPos = (size_t)nNewLen; - m_nDataSize = (size_t)nNewLen; -} - -UINT CZipMemFile::Read(void *lpBuf, UINT nCount) -{ - if (m_nPos > m_nDataSize) - return 0; - UINT nToRead = (m_nPos + nCount > m_nDataSize) ? m_nDataSize - m_nPos : nCount; - memcpy(lpBuf, m_lpBuf + m_nPos, nToRead); - m_nPos += nToRead; - return nToRead; - -} - -void CZipMemFile::Write(const void *lpBuf, UINT nCount) -{ - if (!nCount) - return; - - if (m_nPos + nCount > m_nBufSize) - Grow(m_nPos + nCount); - memcpy(m_lpBuf + m_nPos, lpBuf, nCount); - m_nPos += nCount; - if (m_nPos > m_nDataSize) - m_nDataSize = m_nPos; -} - -ZIP_ULONGLONG CZipMemFile::Seek(ZIP_LONGLONG lOff, int nFrom) -{ - ZIP_ULONGLONG lNew = m_nPos; - - if (nFrom == CZipAbstractFile::begin) - lNew = lOff; - else if (nFrom == CZipAbstractFile::current) - lNew += lOff; - else if (nFrom == CZipAbstractFile::end) - lNew = m_nDataSize + lOff; - else - return lNew; - - if (lNew< 0) - CZipException::Throw(CZipException::memError); - - m_nPos = (size_t)lNew; - return lNew; -} diff --git a/harbour/contrib/hbziparch/zipmemfile.h b/harbour/contrib/hbziparch/zipmemfile.h deleted file mode 100644 index 8501224452..0000000000 --- a/harbour/contrib/hbziparch/zipmemfile.h +++ /dev/null @@ -1,108 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipMemFile.h $ -// $Archive: /ZipArchive/ZipMemFile.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipMemFile.h -* Interface for the CZipMemFile class. -* -*/ -#if !defined(AFX_ZIPMEMFILE_H__EA73AB25_6B51_4C5E_8D78_BAC95812598F__INCLUDED_) -#define AFX_ZIPMEMFILE_H__EA73AB25_6B51_4C5E_8D78_BAC95812598F__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -#include "hbapi.h" -#include "zipabstractfile.h" -#include "zipstring.h" -#include "ZipExport.h" - -/** - A memory buffer which behaves like a physical file. - Automatically grows when necessary -*/ -class ZIP_API CZipMemFile : public CZipAbstractFile -{ -protected: - size_t m_nGrowBy, m_nPos; - size_t m_nBufSize, m_nDataSize; - BYTE* m_lpBuf; - bool m_bAutoDelete; - void Free() - { - if (m_lpBuf) - { - free(m_lpBuf); - m_lpBuf = NULL; - } - } - void Init() - { - m_nGrowBy = m_nPos = 0; - m_nBufSize = m_nDataSize = 0; - m_lpBuf = NULL; - - } - void Grow(size_t nBytes); -public: - bool IsClosed() const { return m_lpBuf == NULL;} - void Flush(){} - - ZIP_ULONGLONG Seek(ZIP_LONGLONG lOff, int nFrom); - ZIP_ULONGLONG GetLength() const {return m_nDataSize;} - void Write(const void* lpBuf, UINT nCount); - UINT Read(void* lpBuf, UINT nCount); - void SetLength(ZIP_ULONGLONG nNewLen); - CZipString GetFilePath() const {return _T("");} - CZipMemFile(long nGrowBy = 1024) - { - Init(); - m_nGrowBy = nGrowBy; - m_bAutoDelete = true; - } - - CZipMemFile(BYTE* lpBuf, UINT nBufSize, long nGrowBy = 0) - { - Init(); - Attach(lpBuf, nBufSize, nGrowBy); - } - ZIP_ULONGLONG GetPosition() const { return m_nPos;} - void Attach(BYTE* lpBuf, UINT nBufSize, long nGrowBy = 0) - { - Close(); - m_lpBuf = lpBuf; - m_nGrowBy = nGrowBy; - m_nBufSize = nBufSize; - m_nDataSize = nGrowBy == 0 ? nBufSize : 0; - m_bAutoDelete = false; - } - BYTE* Detach() - { - BYTE* b = m_lpBuf; - Init(); - return b; - } - void Close() - { - if (m_bAutoDelete) - Free(); - Init(); - } - virtual ~CZipMemFile(){Close();} - -}; - -#endif // !defined(AFX_ZIPMEMFILE_H__EA73AB25_6B51_4C5E_8D78_BAC95812598F__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zippathcomponent.h b/harbour/contrib/hbziparch/zippathcomponent.h deleted file mode 100644 index efaa9bc505..0000000000 --- a/harbour/contrib/hbziparch/zippathcomponent.h +++ /dev/null @@ -1,206 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPathComponent.h $ -// $Archive: /ZipArchive/ZipPathComponent.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipPathComponent.h -* Interface for the CZipPathComponent class. -* -*/ -#if !defined(AFX_ZIPPATHCOMPONENT_H__9B222C08_AD11_4138_96CC_1237511E3E37__INCLUDED_) -#define AFX_ZIPPATHCOMPONENT_H__9B222C08_AD11_4138_96CC_1237511E3E37__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -#include "zipstring.h" -#include "ZipExport.h" - -/** - A class splitting a file path into components. -*/ -class ZIP_API CZipPathComponent -{ -public: - CZipPathComponent(){} - virtual ~CZipPathComponent(); - - static const TCHAR m_cSeparator; ///< A system - specific default path separator. Defined in ZipPlatform.cpp. -/** - Append a path separator to \e szPath if it is not already there. -*/ - static void AppendSeparator(CZipString& szPath) - { - RemoveSeparators(szPath); - szPath += m_cSeparator; - } - - /** - Remove separators from the end of \e szPath - */ - static void RemoveSeparators(CZipString& szPath) - { -// szPath.TrimRight(m_cSeparator); - szPath.TrimRight(_T("\\/")); - } - - /** - Remove separators from the beginning of \e szPath - - */ - - static void RemoveSeparatorsLeft(CZipString& szPath) - { - szPath.TrimLeft(_T("\\/")); - } - - - /** - - \return \c true if \e c is a slash or a backslash - - - */ - static bool IsSeparator(TCHAR c) - { - return c == _T('\\') || c == _T('/'); - } - - /** - \return \c true if the path has a path separator at the and - */ - static bool HasEndingSeparator(const CZipString& szPath) - { - int iLen = szPath.GetLength(); - if (iLen) - return IsSeparator(szPath[iLen - 1]); - else - return false; - } - -/** - Construct the object and set a path. - \param lpszFullPath - the full path of the file - \see SetFullPath -*/ - CZipPathComponent(LPCTSTR lpszFullPath) - { - SetFullPath(lpszFullPath); - } - - // full path of the file (not a directory alone) -/** - Set the path. - \param lpszFullPath - a full path to the file (including a filename - the last element in the - path is assumed to be a filename) -*/ - void SetFullPath(LPCTSTR lpszFullPath); - -/** - \return the filename (without an extension) -*/ - CZipString GetFileTitle() const { return m_szFileTitle;} - -/** - Set the file title (without an extension). - \param lpszFileTitle - - \return -*/ - void SetFileTitle(LPCTSTR lpszFileTitle) { m_szFileTitle = lpszFileTitle;} - - -/** - Set the extension alone. - \param lpszExt - may but not have to contain a dot at the beginning -*/ - void SetExtension(LPCTSTR lpszExt) - { - m_szFileExt = lpszExt; - m_szFileExt.TrimLeft(_T('.')); - } - -/** - \return the file extension without a dot -*/ - CZipString GetFileExt() const { return m_szFileExt;} -/** - \return the drive (no path separator at the end) -*/ - CZipString GetFileDrive() const { return m_szDrive;} -/** - \return the full path without the drive (no separator at the beginning) -*/ - CZipString GetNoDrive() const ; - -/** - \return the filename including an extension -*/ - CZipString GetFileName() const - { - CZipString szFullFileName = m_szFileTitle; - if (!m_szFileExt.IsEmpty()) - { - szFullFileName += _T("."); - szFullFileName += m_szFileExt; - } - return szFullFileName; - } -/** - \return the full path of the file (including the filename) -*/ - CZipString GetFullPath() const - { - CZipString szFullPath = GetFilePath(); - CZipString szFileName = GetFileName(); - if (!szFileName.IsEmpty()) - { - szFullPath += m_cSeparator; - szFullPath += szFileName; - } - return szFullPath; - - } -/** - \return the path of the file (without the separator at the end) -*/ - CZipString GetFilePath() const - { - CZipString szDrive = m_szDrive; - CZipString szDir = m_szDirectory; - if (!szDrive.IsEmpty() && !szDir.IsEmpty()) - szDrive += m_cSeparator; - - return m_szPrefix + szDrive + szDir; - - } -protected: - /** - \name Path components - */ - //@{ - CZipString m_szDirectory, ///< a directory(ies) (one or more) without the path separators at the end and the beginning - m_szFileTitle, ///< a filename without an extension - m_szFileExt, ///< a file extension without a dot - m_szDrive, ///< a drive (if the system path standard uses it) without a path separator at the end - m_szPrefix; ///< a prefix (e.g. for the UNC path or Unicode path under Windows) - //@} - -}; - -#endif // !defined(AFX_ZIPPATHCOMPONENT_H__9B222C08_AD11_4138_96CC_1237511E3E37__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipplatform.h b/harbour/contrib/hbziparch/zipplatform.h deleted file mode 100644 index 52effdd263..0000000000 --- a/harbour/contrib/hbziparch/zipplatform.h +++ /dev/null @@ -1,175 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPlatform.h $ -// $Archive: /ZipArchive/ZipPlatform.h $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipPlatform.h -* ZipPlatform namespace declaration. -* -*/ -#if !defined(AFX_ZipPlatform_H__E2FE6343_9D03_4F3C_A1F7_706C9F0ED978__INCLUDED_) -#define AFX_ZipPlatform_H__E2FE6343_9D03_4F3C_A1F7_706C9F0ED978__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -class CZipFileHeader; -class CZipAutoBuffer; -#include "zipstring.h" -#include "zippathcomponent.h" -#include -#include "ZipExport.h" - -/** - Interface to the system API. - All functions have a system - specific implementation . -*/ -namespace ZipPlatform -{ - - /** - return the default system case-sensitivity - */ - ZIP_API bool GetSystemCaseSensitivity(); - - /** - \return A current system name tag. - May be one of ZipCompatibility::ZipPlatforms values. - \see CZipArchive::GetSystemCompatibility - */ - ZIP_API int GetSystemID(); - -/** - \return the default file attributes for the current system -*/ - ZIP_API DWORD GetDefaultAttributes(); - -/** - \return the default directory attributes for the current system -*/ - ZIP_API DWORD GetDefaultDirAttributes(); - -/** - Get the free space on the device pointed by \e lpszPath -*/ - ZIP_API DWORD GetDeviceFreeSpace(LPCTSTR lpszPath); - -/** - Return the temporary file name ensuring there is enough size in the destination directory,. - Checking for the size is disabled by default. -*/ - ZIP_API CZipString GetTmpFileName(LPCTSTR lpszPath = NULL, DWORD iSizeNeeded = DWORD(-1)); -/** - \name Various operations on files and directories. - All the functions which are returning a \c bool value, - return \c true when the operation was successful. -*/ - //@{ - ZIP_API bool GetCurrentDirectory(CZipString& sz); ///< Get the current directory and store it in \e sz - ZIP_API bool ChangeDirectory(LPCTSTR lpDirectory); - ZIP_API bool SetFileAttr(LPCTSTR lpFileName, DWORD uAttr); - ZIP_API bool GetFileAttr(LPCTSTR lpFileName, DWORD& uAttr); - ZIP_API bool GetFileModTime(LPCTSTR lpFileName, time_t & ttime); ///< get the file modification time - ZIP_API bool GetFileSize(LPCTSTR lpszFileName, DWORD& dSize); - ZIP_API bool SetFileModTime(LPCTSTR lpFileName, time_t ttime); ///< set the file modification time - ZIP_API bool CreateDirectory(LPCTSTR lpDirectory); - ZIP_API bool SetVolLabel(LPCTSTR lpszPath, LPCTSTR lpszLabel); ///< \c lpszPath may point to a file on the device - ZIP_API bool ForceDirectory(LPCTSTR lpDirectory); ///< create nested directories at once - ZIP_API bool RemoveFile(LPCTSTR lpszFileName, bool bThrow = true); - ZIP_API bool RenameFile( LPCTSTR lpszOldName, LPCTSTR lpszNewName, bool bThrow = true); - -#ifndef _MFC_VER - ZIP_API bool TruncateFile(int iDes, DWORD iSize); - ZIP_API int OpenFile(LPCTSTR lpszFileName, UINT iMode, int iShareMode); - ZIP_API bool FlushFile(int iDes); ///< flush the file to the disk. - ZIP_API int GetFileSystemHandle(int iDes); ///< return the underlying system handle -#endif - //@} - -/** - \param lpszDir - - \return \c true, if \e lpszDir directory exists; otherwise \c false; -*/ - ZIP_API bool DirectoryExists(LPCTSTR lpszDir); -/** - \param lpszFilePath - may point to a file path or a directory on the device - \return \c true if the drive is removable. - Implemented only on Windows system, in all others always returns \c true. -*/ - ZIP_API bool IsDriveRemovable(LPCTSTR lpszFilePath); -/** - \param uAttr - attributes value to test - \return \c true if the attributes are the directory attributes -*/ - ZIP_API bool IsDirectory(DWORD uAttr); - -/** - Perform the translation between ANSI and OEM character sets. - \remark - - The conversion is performed only for the zip archives created under Windows platform. - - Windows archiving programs convert a filename to OEM before adding it to the archive. - - OEM conversion only influences the ANSI values above 126, so it - affects only strings containing international characters. - - \param buffer - buffer to be translated - \param bAnsiToOem - if \c true, convert ANSI to OEM - if \c false, OEM to ANSI -*/ - ZIP_API void AnsiOem(CZipAutoBuffer& buffer, bool bAnsiToOem); -/** - Check if the given file or directory exists. - \param lpszName - - \return - - -1 if the given file is a directory - - 1 a file - - 0 if there is no such a file -*/ - ZIP_API int FileExists(LPCTSTR lpszName); - - -#ifdef _UNICODE -/** - Convert wide character string to single character string. - \param lpWide - Wide string to convert - \param szSingle - buffer to receive converted string (without the terminating NULL character) - \return - the \e szSingle buffer length, or \c -1 when not succeeded - \note Only in UNICODE version. -*/ - ZIP_API int WideToSingle(LPCTSTR lpWide, CZipAutoBuffer &szSingle); -/** - Convert single character string to wide character string. - \param szSingle - single string to convert (no terminating NULL character at the end) - \param szWide - receives the wide string after the conversion - \return \e the length of the string after the conversion (without the NULL character), - or \c -1 when not succeeded - \note Only in UNICODE version. -*/ - ZIP_API int SingleToWide(const CZipAutoBuffer &szSingle, CZipString& szWide); -#endif -}; - - -#endif // !defined(AFX_ZipPlatform_H__E2FE6343_9D03_4F3C_A1F7_706C9F0ED978__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipplatformcomm.cpp b/harbour/contrib/hbziparch/zipplatformcomm.cpp deleted file mode 100644 index f9403b9d91..0000000000 --- a/harbour/contrib/hbziparch/zipplatformcomm.cpp +++ /dev/null @@ -1,49 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipPlatformComm.cpp $ -// $Archive: /ZipArchive/ZipPlatformComm.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - - -#include "stdafx.h" -#include "zipplatform.h" - -using namespace ZipPlatform; - -bool ZipPlatform::DirectoryExists(LPCTSTR lpszDir) -{ - CZipString sz; - if (!GetCurrentDirectory(sz)) - return false; - if (!ChangeDirectory(lpszDir)) - return false; - ChangeDirectory(sz); - return true; -} - -bool ZipPlatform::ForceDirectory(LPCTSTR lpDirectory) -{ - ASSERT(lpDirectory); - CZipString szDirectory = lpDirectory; - szDirectory.TrimRight(CZipPathComponent::m_cSeparator); - CZipPathComponent zpc(szDirectory); - - if ((zpc.GetFilePath() == (LPCTSTR) szDirectory) || - (FileExists(szDirectory) == -1)) - return true; - if (!ForceDirectory(zpc.GetFilePath())) - return false; - if (!CreateDirectory(szDirectory)) - return false; - return true; -} diff --git a/harbour/contrib/hbziparch/zipstorage.cpp b/harbour/contrib/hbziparch/zipstorage.cpp deleted file mode 100644 index a26036b6bc..0000000000 --- a/harbour/contrib/hbziparch/zipstorage.cpp +++ /dev/null @@ -1,463 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipStorage.cpp $ -// $Archive: /ZipArchive/ZipStorage.cpp $ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#include "stdafx.h" -#include "zipstorage.h" -#include "ziparchive.h" -// #include "ZipPathComponent.h" -#include "zipplatform.h" - -////////////////////////////////////////////////////////////////////// -// disk spanning objectives: -// - sinature at the first disk at the beginning -// - headers and central dir records not divided between disks -// - each file has a data descriptor preceded by the signature -// (bit 3 set in flag); - -int CZipActionCallback::m_iStep = 256; - -char CZipStorage::m_gszExtHeaderSignat[] = {0x50, 0x4b, 0x07, 0x08}; -CZipStorage::CZipStorage() -{ - m_pChangeDiskFunc = NULL; - m_iWriteBufferSize = 65536; - m_iCurrentDisk = -1; - m_pFile = NULL; -} - -CZipStorage::~CZipStorage() -{ - -} - -DWORD CZipStorage::Read(void *pBuf, DWORD iSize, bool bAtOnce) -{ - if (iSize == 0) - return 0; - DWORD iRead = 0; - while (!iRead) - { - iRead = m_pFile->Read(pBuf, iSize); - if (!iRead) - { - if (IsSpanMode()) - ChangeDisk(m_iCurrentDisk + 1); - else - ThrowError(CZipException::badZipFile); - } - } - - if (iRead == iSize) - return iRead; - else if (bAtOnce || !IsSpanMode()) - ThrowError(CZipException::badZipFile); - - while (iRead < iSize) - { - ChangeDisk(m_iCurrentDisk + 1); - UINT iNewRead = m_pFile->Read((char*)pBuf + iRead, iSize - iRead); - if (!iNewRead && iRead < iSize) - ThrowError(CZipException::badZipFile); - iRead += iNewRead; - } - - return iRead; -} - -void CZipStorage::Open(LPCTSTR szPathName, int iMode, int iVolumeSize) -{ - m_pWriteBuffer.Allocate(m_iWriteBufferSize); - m_uBytesInWriteBuffer = 0; - m_bNewSpan = false; - m_pFile = &m_internalfile; - m_bInMemory = false; - - if ((iMode == CZipArchive::zipCreate) ||(iMode == CZipArchive::zipCreateSpan)) // create new archive - { - m_bReadOnly = false; - m_iCurrentDisk = 0; - if (iMode == CZipArchive::zipCreate) - { - m_iSpanMode = noSpan; - OpenFile(szPathName, CZipFile::modeCreate | CZipFile::modeReadWrite); - } - else // create disk spanning archive - { - m_bNewSpan = true; - m_iBytesWritten = 0; - if (iVolumeSize <= 0) // pkzip span - { - if (!m_pChangeDiskFunc) - ThrowError(CZipException::noCallback); - if (!ZipPlatform::IsDriveRemovable(szPathName)) - ThrowError(CZipException::nonRemovable); - m_iSpanMode = pkzipSpan; - } - else - { - m_iTdSpanData = iVolumeSize; - m_iSpanMode = tdSpan; - } - - NextDisk(4, szPathName); - Write(m_gszExtHeaderSignat, 4, true); - } - } - else // open existing - { - m_bReadOnly = iMode == CZipArchive::zipOpenReadOnly; - OpenFile(szPathName, CZipFile::modeNoTruncate | - (m_bReadOnly ? CZipFile::modeRead : CZipFile::modeReadWrite)); - // m_uData, i m_iSpanMode are automatically set during reading the central dir - m_iSpanMode = iVolumeSize == 0 ? suggestedAuto : suggestedTd; - } - -} - - -void CZipStorage::Open(CZipMemFile& mf, int iMode) -{ - m_pWriteBuffer.Allocate(m_iWriteBufferSize); - m_uBytesInWriteBuffer = 0; - m_bNewSpan = false; - m_pFile = &mf; - m_bInMemory = true; - - if (iMode == CZipArchive::zipCreate) - { - m_iCurrentDisk = 0; - m_iSpanMode = noSpan; - mf.SetLength(0); - } - else // open existing - { - mf.SeekToBegin(); - m_iSpanMode = suggestedAuto; - } -} - - -void CZipStorage::ChangeDisk(int iNumber) -{ - if (iNumber == m_iCurrentDisk) - return; - - ASSERT(m_iSpanMode != noSpan); - m_iCurrentDisk = iNumber; - OpenFile(m_iSpanMode == pkzipSpan ? ChangePkzipRead() : ChangeTdRead(), - CZipFile::modeNoTruncate | CZipFile::modeRead); -} - -void CZipStorage::ThrowError(int err) -{ - CZipException::Throw(err, m_pFile->GetFilePath()); -} - -bool CZipStorage::OpenFile(LPCTSTR lpszName, UINT uFlags, bool bThrow) -{ - return m_pFile->Open(lpszName, uFlags | CZipFile::shareDenyWrite, bThrow); -} - - -CZipString CZipStorage::ChangePkzipRead() -{ - CZipString szTemp = m_pFile->GetFilePath(); - m_pFile->Close(); - CallCallback(-1 , szTemp); - return szTemp; -} - -CZipString CZipStorage::ChangeTdRead() -{ - CZipString szTemp = GetTdVolumeName(m_iCurrentDisk == m_iTdSpanData); - m_pFile->Close(); - return szTemp; -} - -CZipString CZipStorage::RenameLastFileInTDSpan() -{ - ASSERT(m_iSpanMode == tdSpan); - // give to the last volume the zip extension - CZipString szFileName = m_pFile->GetFilePath(); - CZipString szNewFileName = GetTdVolumeName(true); - if (!m_bInMemory) - { - m_pFile->Flush(); - m_pFile->Close(); - } - if (ZipPlatform::FileExists(szNewFileName)) - ZipPlatform::RemoveFile(szNewFileName); - ZipPlatform::RenameFile(szFileName, szNewFileName); - return szNewFileName; -} - -CZipString CZipStorage::Close(bool bAfterException) -{ - bool bClose = true; - CZipString sz; - if (!bAfterException) - { - Flush(); - if ((m_iSpanMode == tdSpan) && (m_bNewSpan)) - { - sz = RenameLastFileInTDSpan(); - bClose = false;// already closed in RenameLastFileInTDSpan - } - } - if (sz.IsEmpty()) - sz = m_pFile->GetFilePath(); - if (bClose && !m_bInMemory) - { - FlushFile(); - m_pFile->Close(); - } - - - - m_pWriteBuffer.Release(); - m_iCurrentDisk = -1; - m_iSpanMode = noSpan; - m_pFile = NULL; - return sz; -} - -CZipString CZipStorage::GetTdVolumeName(bool bLast, LPCTSTR lpszZipName) const -{ - CZipString szFilePath = lpszZipName ? lpszZipName : (LPCTSTR)m_pFile->GetFilePath(); - CZipPathComponent zpc(szFilePath); - CZipString szExt; - if (bLast) - szExt = m_szSpanExtension; - else - szExt.Format(_T("%.3d"), m_iCurrentDisk); - zpc.SetExtension(szExt); - return zpc.GetFullPath(); -} - -void CZipStorage::NextDisk(int iNeeded, LPCTSTR lpszFileName) -{ - Flush(); - ASSERT(m_iSpanMode != noSpan); - if (m_iBytesWritten) - { - m_iBytesWritten = 0; - m_iCurrentDisk++; - if (m_iCurrentDisk >= 999) - ThrowError(CZipException::tooManyVolumes); - } - CZipString szFileName; - bool bPkSpan = (m_iSpanMode == pkzipSpan); - if (bPkSpan) - szFileName = lpszFileName ? lpszFileName : (LPCTSTR)m_pFile->GetFilePath(); - else - szFileName = GetTdVolumeName(false, lpszFileName); - - if (!m_pFile->IsClosed()) - { - m_pFile->Flush(); - m_pFile->Close(); - } - - if (bPkSpan) - { - int iCode = iNeeded; - while (true) - { - CallCallback(iCode, szFileName); - if (ZipPlatform::FileExists(szFileName)) - iCode = -2; - else - { - CZipString label; - label.Format(_T("pkback# %.3d"), m_iCurrentDisk + 1); - if (!ZipPlatform::SetVolLabel(szFileName, label)) - iCode = -3; - else if (!OpenFile(szFileName, CZipFile::modeCreate | CZipFile::modeReadWrite, false)) - iCode = -4; - else - break; - } - - } - m_uCurrentVolSize = GetFreeVolumeSpace(); - } - else - { - m_uCurrentVolSize = m_iTdSpanData; - OpenFile(szFileName, CZipFile::modeCreate | CZipFile::modeReadWrite); - } -} - -void CZipStorage::CallCallback(int iCode, CZipString szTemp) -{ - ASSERT(m_pChangeDiskFunc); - m_pChangeDiskFunc->m_szExternalFile = szTemp; - m_pChangeDiskFunc->m_uDiskNeeded = m_iCurrentDisk + 1; - if (!m_pChangeDiskFunc->Callback(iCode)) - CZipException::Throw(CZipException::aborted, szTemp); -} - -DWORD CZipStorage::GetFreeVolumeSpace() const -{ - ASSERT (m_iSpanMode == pkzipSpan); - CZipString szTemp = m_pFile->GetFilePath(); - if (szTemp.IsEmpty()) // called once when creating a disk spanning archive - return 0; - else - { - CZipPathComponent zpc(szTemp); - return ZipPlatform::GetDeviceFreeSpace(zpc.GetFilePath()); - } -} - - -void CZipStorage::UpdateSpanMode(WORD uLastDisk) -{ - m_iCurrentDisk = uLastDisk; - if (uLastDisk) - { - // disk spanning detected - CZipString szFilePath = m_pFile->GetFilePath(); - if (m_iSpanMode == suggestedAuto) - m_iSpanMode = ZipPlatform::IsDriveRemovable(szFilePath) ? - pkzipSpan : tdSpan; - else - { - ASSERT(m_iSpanMode == suggestedTd); - m_iSpanMode = tdSpan; - } - - if (m_iSpanMode == pkzipSpan) - { - if (!m_pChangeDiskFunc) - ThrowError(CZipException::noCallback); - } - else /*if (m_iSpanMode == tdSpan)*/ - m_iTdSpanData = uLastDisk; // disk with .zip extension ( the last one) - CZipPathComponent zpc(szFilePath); - m_szSpanExtension = zpc.GetFileExt(); - m_pWriteBuffer.Release(); // no need for this in this case - } - else - m_iSpanMode = noSpan; - -} - -void CZipStorage::Write(const void *pBuf, DWORD iSize, bool bAtOnce) -{ - if (!IsSpanMode()) - WriteInternalBuffer((char*)pBuf, iSize); - else - { - // if not at once, one byte is enough free space - DWORD iNeeded = bAtOnce ? iSize : 1; - DWORD uTotal = 0; - - while (uTotal < iSize) - { - DWORD uFree; - while ((uFree = VolumeLeft()) < iNeeded) - { - if ((m_iSpanMode == tdSpan) && !m_iBytesWritten && !m_uBytesInWriteBuffer) - // in the tdSpan mode, if the size of the archive is less - // than the size of the packet to be written at once, - // increase once the size of the volume - m_uCurrentVolSize = iNeeded; - else - NextDisk(iNeeded); - } - - DWORD uLeftToWrite = iSize - uTotal; - DWORD uToWrite = uFree < uLeftToWrite ? uFree : uLeftToWrite; - WriteInternalBuffer((char*)pBuf + uTotal, uToWrite); - if (bAtOnce) - return; - else - uTotal += uToWrite; - } - - } -} - - -void CZipStorage::WriteInternalBuffer(const char *pBuf, DWORD uSize) -{ - DWORD uWritten = 0; - while (uWritten < uSize) - { - DWORD uFreeInBuffer = GetFreeInBuffer(); - if (uFreeInBuffer == 0) - { - Flush(); - uFreeInBuffer = m_pWriteBuffer.GetSize(); - } - DWORD uLeftToWrite = uSize - uWritten; - DWORD uToCopy = uLeftToWrite < uFreeInBuffer ? uLeftToWrite : uFreeInBuffer; - memcpy(m_pWriteBuffer + m_uBytesInWriteBuffer, pBuf + uWritten, uToCopy); - uWritten += uToCopy; - m_uBytesInWriteBuffer += uToCopy; - } -} - -DWORD CZipStorage::VolumeLeft() const -{ - // for pkzip span m_uCurrentVolSize is updated after each flush() - return m_uCurrentVolSize - m_uBytesInWriteBuffer - ((m_iSpanMode == pkzipSpan) ? 0 : m_iBytesWritten); -} - -void CZipStorage::Flush() -{ - if (m_iSpanMode != noSpan) - m_iBytesWritten += m_uBytesInWriteBuffer; - if (m_uBytesInWriteBuffer) - { - m_pFile->Write(m_pWriteBuffer, m_uBytesInWriteBuffer); - m_uBytesInWriteBuffer = 0; - } - if (m_iSpanMode == pkzipSpan) - // after writing it is difficult to predict the free space due to - // not completly written clusters, write operation may start from - // the new cluster - m_uCurrentVolSize = GetFreeVolumeSpace(); - -} - - - -void CZipStorage::FinalizeSpan() -{ - ASSERT(IsSpanMode() == 1); // span in creation - ASSERT(!m_bInMemory); - - CZipString szFileName; - if ((m_iSpanMode == tdSpan) && (m_bNewSpan)) - szFileName = RenameLastFileInTDSpan(); - else - { - szFileName = m_pFile->GetFilePath(); - // the file is already closed - m_pFile->Close(); - } - m_bNewSpan = false; - if (m_iCurrentDisk == 0) // one-disk span was converted to normal archive - m_iSpanMode = noSpan; - else - m_iTdSpanData = m_iCurrentDisk; - - OpenFile(szFileName, CZipFile::modeNoTruncate | (m_iSpanMode == noSpan ? CZipFile::modeReadWrite : CZipFile::modeRead)); - -} - diff --git a/harbour/contrib/hbziparch/zipstorage.h b/harbour/contrib/hbziparch/zipstorage.h deleted file mode 100644 index aeaf8ddcdd..0000000000 --- a/harbour/contrib/hbziparch/zipstorage.h +++ /dev/null @@ -1,588 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $Workfile: ZipStorage.h $ -// $Archive: /ZipArchive/ZipStorage.h $ -// $Date$ $Author$. -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -/** -* \file ZipStorage.h -* Interface for the CZipStorage class. -* -*/ - -#if !defined(AFX_ZIPSTORAGE_H__941824FE_3320_4794_BDE3_BE334ED8984B__INCLUDED_) -#define AFX_ZIPSTORAGE_H__941824FE_3320_4794_BDE3_BE334ED8984B__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "zipfile.h" -#include "zipautobuffer.h" -#include "zipstring.h" -#include "zipmemfile.h" -#include "ZipExport.h" - - - -/** - A base class for functional objects (functors) that are used as a callbacks during various actions. - You need to derive your own class and overload \c Callback method to use it. - Do not derive from CZipCallback directly but from CZipSpanCallback (as a callback when there is a need - for a disk change in a disk-spanning archive) or from CZipActionCallback for other actions. -*/ -struct ZIP_API CZipCallback -{ - /** - Method called as a callback. - Return \c false from inside the method to abort the current operation. If it is a span callback functor, - a CZipException with CZipException::aborted code will be thrown, otherwise the code will be CZipException::abortedAction or CZipException::abortedSafely. - The following actions can be safely aborted (without having the archive corrupted): - - counting bytes before deleting files - - testing - - saving central directory on non-disk-spanning archive - (saved data is removed in case of break and you can save it again); - it the archive is disk-spanning and if saving is aborted, the archive - will not be damaged, but saved part of the central directory will be not removed - and the new central directory will have to be saved after it - - \note Overrride this method in the derived class. If you define this method inside the class declaration, it should be inlined - by the compiler making the action progress faster. - */ - virtual bool Callback(int iProgress) = 0; - - - CZipString m_szExternalFile; ///< if the action (adding, extracting or disk-spanning) uses an external file, its filename is stored here -}; - -/** - Derive from this a class to be used as a callback functor for the disk change callback. - You need to override member function CZipCallback::Callback. The meaning of \e iProgress parameter is the reason for calling: - - -1 : a disk needed for reading
- other codes occurs during writing: - - >=0 : min. number of bytes needed - - -2 : the file with the archive name already exists on the disk - - -3 : the disk is probably write - protected - - -4 : couldn't create a file - - - Return \c false from the callback function to abort operation: the proper exception will be thrown. - - \see CZipCallback::Callback - \see CZipArchive::SetSpanCallback -*/ -struct ZIP_API CZipSpanCallback : public CZipCallback -{ - DWORD m_uDiskNeeded; ///< the number of a disk needed (counting from 1) -}; - - - -/** - Derive from this a class to be used as a callback functors when adding, extracting, deleting, testing a file - or saving central directory. - You need to override member function CZipCallback::Callback. The meaning of \e iProgress parameter is the count - of data just processed. It is a smallest number of bytes after which the callback method is called and it depends - on the value of \e nBufSize in the CZipArchive methods that uses the callback feature. In case of saving the central - directory action it is the count of file headers just written (see CZipArchive::cbSave) - \see CZipCallback::Callback - \see CZipArchive::SetCallback -*/ -struct ZIP_API CZipActionCallback : public CZipCallback -{ - - CZipActionCallback() - { - m_uTotalToDo = 0; - m_uTotalSoFar = 0; - } - - /** - The type of the callback. It is set to one of CZipArchive::CallbackType values when the action begins. - It's useful if you have more than one callback assigned to the same functor. - */ - int m_iType; - - /** - Used by the ZipArchive library to init the callback function with the filenames. Resets #m_uTotalToDo and #m_uTotalSoFar variables to 0. - #m_iType variable is already set to the proper value. Called at the beginning of the action. - */ - virtual void Init(LPCTSTR lpszFileInZip = NULL, LPCTSTR lpszExternalFile = NULL) - { - m_szFileInZip = lpszFileInZip; - m_szExternalFile = lpszExternalFile; - m_uTotalToDo = 0; // not yet known - m_uTotalSoFar = 0; // nothing yet done - } - - /** - Called by the ZipArchive functions that use the callback feature after calculating total data to process. - \param uTotalToDo - total data to process; set #m_uTotalToDo to this value - */ - virtual void SetTotal(DWORD uTotalToDo) - { - m_uTotalToDo = uTotalToDo; -// m_uTotalSoFar = 0; // already done in CZipArchive::CZipClbckStrg::Get - } - - - - /** - Total number of data to process. The value of this variable is set after calling by the library #SetTotal method (it is 0 before). - Depending on the action it is set then to: - - adding file: the size the external file being added (or if callback is CZipArchive::cbAddTmp, the size of compressed data: CZipFileHeader::m_uComprSize) - - extracting file: the size of uncompressed data (CZipFileHeader::m_uUncomprSize) - - testing file: the same as above - - deleting file: the count of bytes to move - the size of all files to remain above the first file to delete (calculated from offsets CZipFileHeader::m_uOffset - - saving central directory: the number of files in the archive - - */ - DWORD m_uTotalToDo; - DWORD m_uTotalSoFar; ///< total number of bytes processed so far - CZipString m_szFileInZip; ///< file in zip archive being currently processed - - - /** - \return the number of bytes left to process - */ - DWORD LeftToDo() {return m_uTotalToDo - m_uTotalSoFar;} - - - /** - Called after the action finishes (it is not called in case of an exception, but - it is called before throwing CZipException::abortedAction or CZipException::abortedSafely) - */ - virtual void CallbackEnd() - { - ASSERT(m_uTotalSoFar == m_uTotalToDo); - }; - - /** - Used internally to call Callback and increase #m_uTotalSoFar by \e iProgress - */ - virtual bool operator()(int iProgress) - { - m_uTotalSoFar += iProgress; - return Callback(iProgress); - } - - /** - Used only when creating map before deletion (see CZipArchive::cbDeleteCnt) or - saving the central directory record. You'll be notified every nth step (n is \e m_iStep value) with \e iProgress set to - \e m_iStep . Do not set it to low values or you can have a long waiting on archives - with huge number of files. - - \b Default: 256. - */ - static int m_iStep; - - - /** - Used internally to return #m_iStep value but not 0 (return 1 in this case). - */ - int GetStep(){return m_iStep ? m_iStep : 1;} // do not allow 0 (crash) - -}; - - -/** - A low-level class - operates physically on archive (CZipArchive operates logically) -*/ -class ZIP_API CZipStorage -{ - friend class CZipCentralDir; -public: - - /** - The type of the disk spanning archive. - \see CZipArchive::GetSpanMode - */ - enum ZipSpanMode { - noSpan, ///< no disk spanning - pkzipSpan, ///< \ref PKSpan "disk spanning compatible with PKZIP" - tdSpan, ///< \ref TDSpan "TD mode disk spanning archive" - /** - Detect the type automatically. - If the archive is on the removable device assume PKZIP compatible, - otherwise TD mode compatible. - */ - suggestedAuto, - /** - If the disk spanning archive is on the removable device - assume it is TD mode compatible - */ - suggestedTd - }; - - CZipStorage(); - virtual ~CZipStorage(); - -/** - Open the archive in memory (new or existing). - The parameters are the same as CZipArchive::OpenMode. - \param mf - \param iMode - \note Throws exceptions. - - \see CZipArchive::Open(LPCTSTR, int, int) -*/ - void Open(CZipMemFile& mf, int iMode); - -/** - Open or create an archive. - The parameters are the same as CZipArchive::Open. - \param szPathName - \param iMode - \param iVolumeSize - \note Throws exceptions. - - \see CZipArchive::Open(CZipMemFile& , int); -*/ - void Open(LPCTSTR szPathName, int iMode, int iVolumeSize); - - - /** - Close the disk-spanning archive and reopens as an existing disk-spanning archive or set mode to #noSpan - */ - void FinalizeSpan(); - - -/** - Called only by CZipCentralDir::Read() when opening an existing archive. - \param uLastDisk - the disk number the central directory is on - \note Throws exceptions. - -*/ - void UpdateSpanMode(WORD uLastDisk); - - -/** - Write chunk of data to the archive. - \param pBuf - buffer with data - \param iSize - bytes to write - \param bAtOnce - if \c true, the whole data must fit in the current volume, - otherwise the disk change is performed - \note Throws exceptions. -*/ - void Write(const void *pBuf, DWORD iSize, bool bAtOnce); - -/** - Read chunk of data from the archive. - \param pBuf - buffer to receive data - \param iSize - bytes to read - \param bAtOnce - if \c true, the specified number of bytes must be read from the same - volume (no disk change allowed) - \note Throws exceptions. -*/ - DWORD Read(void* pBuf, DWORD iSize, bool bAtOnce); - - /** - Return the position in the file, taking into account the bytes in the write buffer. - \note Throws exceptions. - */ - DWORD GetPosition() const {return (DWORD)(m_pFile->GetPosition()) + m_uBytesInWriteBuffer;} - - - /** - Flush the data from the read buffer to the disk. - \note Throws exceptions. - */ - void Flush(); - - - /** - Forces any data remaining in the file buffer to be written to the disk - */ - void FlushFile() - { - if (!m_bInMemory && !IsReadOnly()) - m_pFile->Flush(); - } - -/** - A method used to change disks during writing to the disk spanning archive. - \param iNeeded - no of bytes needed on the disk - \param lpszFileName - the archive filename - \note Throws exceptions. -*/ - void NextDisk(int iNeeded, LPCTSTR lpszFileName = NULL); - - -/** - \return a zero-based number of the current disk -*/ - int GetCurrentDisk() const {return m_iCurrentDisk;} - - -/** - Change the disk during extract operations. - \param iNumber - a zero-based disk number requested - \return -*/ - void ChangeDisk(int iNumber); - -/** - Detect the span mode. - \return - - -1 - existing disk spanning archive opened - - 0 - no disk spanning archive - - 1 - disk spanning archive in creation - -*/ - int IsSpanMode() const - { - return m_iSpanMode == noSpan ? 0 : (m_bNewSpan ? 1 : -1); - } - - /** - return \c true if the archive cannot be modified. - */ - bool IsReadOnly() - { - return m_bReadOnly || IsSpanMode() < 0; - } - -/** - - \param bAfterException - set to \c true after the library has throw an exception. - The simplified mode is used then. - In this case it'll be possible to reuse the object to operate on another - archive, but the current archive file will not be valid anyway. - \return the filepath of the archive (used by CZipArchive::Close) - \note Throws exceptions. -*/ - CZipString Close(bool bAfterException); - - - /** - The size of the write buffer. - Set before opening the archive. - It is usually set with CZipArchive::SetAdvanced - (specify this value as the first argument). - \see CZipArchive::SetAdvanced - */ - int m_iWriteBufferSize; - - - /** - The physical archive file (on a storage device). - Not used when opening archive in memory - with Open(CZipMemFile& , int). - */ - CZipFile m_internalfile; - - /** - The buffer representing the archive. - It is a physical file or a memory buffer depending on what - method was used to open the archive. In the first case it is - a pointer to #m_internalfile. - \see Open(LPCTSTR, int, int); - \see Open(CZipMemFile& mf, int) - - */ - CZipAbstractFile* m_pFile; - - /** - Takes one of the values of #ZipSpanMode. - */ - int m_iSpanMode; - - /** - A callback functor which method \c Callback is called when there is a need for a disk change - while operating on a #pkzipSpan archive. - \see CZipArchive::SetSpanCallback - */ - CZipSpanCallback* m_pChangeDiskFunc; - - /** - The signature of the extended header - */ - static char m_gszExtHeaderSignat[]; -protected: - - /** - Flush without writing. Can be used only on non-disk spanning archives. - */ - void EmptyWriteBuffer() - { - m_uBytesInWriteBuffer = 0; - } - -/** - Open a physical file. - \param lpszName - the name of the file to open - \param uFlags - file open flags - \param bThrow - if \c true then throw an exception in case of failure - \return \c true if successful -*/ - bool OpenFile(LPCTSTR lpszName, UINT uFlags, bool bThrow = true); -/** - Throw an exception with the given code. - \param err - \see CZipException::Throw -*/ - void ThrowError(int err); - -/** - Return the number of bytes left on the current volume. -*/ - DWORD VolumeLeft() const; - - /** - Rename last file in TD mode disk spanning archive when done with creating - */ - CZipString RenameLastFileInTDSpan(); -/** - Write data to the internal buffer. - \param *pBuf - the buffer to copy data from - \param uSize - bytes to write - \note Throws exceptions. -*/ - void WriteInternalBuffer(const char *pBuf, DWORD uSize); - -/** - \return the number of free bytes on the current removable disk -*/ - DWORD GetFreeVolumeSpace() const; - -/** - Call the callback functor. - Throw an exception if the callback functor's method \c Callback returns \c false. - \param iCode - a code to be passed to the callback functor - \param szTemp - a string to be used as a filename (the second argument - of CZipException::Throw) when the exception must be thrown - \note Throws exceptions. - \see CZipArchive::SetSpanCallback - \see CZipException::Throw -*/ - void CallCallback(int iCode, CZipString szTemp); - - -/** - Construct the name of the volume in #tdSpan mode. - \param bLast - must be \c true if constructing the last volume name (an extension "zip" is given) - \param lpszZipName - the name of the archive - \return - the new volume name -*/ - CZipString GetTdVolumeName(bool bLast, LPCTSTR lpszZipName = NULL) const; - - /** - Change the disk in #tdSpan mode - */ - CZipString ChangeTdRead(); - - /** - Change the disk in #pkzipSpan mode - */ - CZipString ChangePkzipRead(); - - - /** - Used only in \ref TDSpan "TD span mode" . The value it holds depends on the open mode. - - Opened existing disk spanning archive - store the number of the last - disk ( the one with "zip" extension). - - Disk spanning archive in creation - the size of the volume. - - \see CZipArchive::Open - \see CZipArchive::GetSpanMode - - */ - int m_iTdSpanData; - - /** - The extension of the last volume. - */ - CZipString m_szSpanExtension; - - /** - \return the count bytes left free in the write buffer - */ - DWORD GetFreeInBuffer() const {return m_pWriteBuffer.GetSize() - m_uBytesInWriteBuffer;} - - /** - Number of bytes available in the write buffer. - */ - DWORD m_uBytesInWriteBuffer; - -/** - The value it holds depends on the open mode: - \par - - #tdSpan : the total size of the current volume - - #pkzipSpan: a free space on the current volume -*/ - DWORD m_uCurrentVolSize; - - - /** - number of bytes left free in the write buffer - */ - DWORD m_uVolumeFreeInBuffer; - - /** - Write buffer caching data. - */ - CZipAutoBuffer m_pWriteBuffer; - - - /** - Used only during disk spanning archive creation. - Tells how many bytes have been written physically to the current volume. - */ - DWORD m_iBytesWritten; - - /** - \c True, if the current archive is a new disk spanning archive. - */ - bool m_bNewSpan; - - /** - The current disk in a disk spanning archive. - Disk no 0 is the first disk. - */ - int m_iCurrentDisk; - - /** - It is set to \e true when an archive is created in memory; \e false otherwise. - */ - bool m_bInMemory; - - /** - It is set to \e true if OpenMode::zipOpenReadOnly was specified when opening the archive - */ - bool m_bReadOnly; - -}; - -#endif // !defined(AFX_ZIPSTORAGE_H__941824FE_3320_4794_BDE3_BE334ED8984B__INCLUDED_) diff --git a/harbour/contrib/hbziparch/zipstring.h b/harbour/contrib/hbziparch/zipstring.h deleted file mode 100644 index f125b36e76..0000000000 --- a/harbour/contrib/hbziparch/zipstring.h +++ /dev/null @@ -1,310 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// $RCSfile$ -// $Revision$ $Name$ -// $Date$ $Author$ -//////////////////////////////////////////////////////////////////////////////// -// This source file is part of the ZipArchive library source distribution and -// is Copyrighted 2000-2005 by Tadeusz Dracz (http://www.artpol-software.com/) -// -// 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. -// -// For the licensing details see the file License.txt -//////////////////////////////////////////////////////////////////////////////// - -#ifndef __ZIPSTRING_H__ -#define __ZIPSTRING_H__ -#include "stdafx.h" - -#if defined(_MSC_VER) && (_MSC_VER > 1100) - #pragma warning( push, 3 ) // STL requrements -#endif - -/** - If you wish the class to respect your locale (if it is different from - English), you need to set it in your program with function - std::locale::global(std::locale("")) (to set it to be the same as your - system locale) or e.g. std::locale::global(std::locale("French")) - ( to set it to a specified value); setlocale() function is not sufficient here. -*/ - -#define _USE_OLD_RW_STL -#include -#include -#include -#include -#include - -#include "ZipExport.h" - -#ifndef __GNUC__ - #ifndef _vsntprintf - #ifdef _UNICODE - #define _vsntprintf _vsnwprintf - #else - #define _vsntprintf _vsnprintf - #endif - #endif -#include -#else - #define _vsntprintf vsnprintf -#endif - - - -typedef std::basic_string stdbs; -/** - This is not a full MFC - CString replacement. - For now it contains mostly the methods required by ZipArchive library. -*/ -class ZIP_API CZipString : public stdbs -{ - void TrimInternalL(size_type iPos) - { - if (iPos == npos) - erase (); - if (iPos) - erase(0, iPos); - } - void TrimInternalR(size_type iPos) - { - if (iPos == npos) - erase (); - erase(++iPos); - } -#ifndef __GNUC__ - static int zslen(const TCHAR* lpsz) - { - if (!lpsz) return 0; - - // we want to take into account the locale stuff (by using standard templates) - - #ifdef _UNICODE - return std::wstring(lpsz).length(); - #else - return std::string(lpsz).length(); - #endif - } - static TCHAR tl(TCHAR c) - { - // use_facet doesn't work here well (doesn't convert all the local characters properly) - return std::tolower(c, std::locale()); - } - static TCHAR tu(TCHAR c) - { - // use_facet doesn't work here well (doesn't convert all the local characters properly) - return std::toupper(c, std::locale()); - } -#else - static int zslen(const TCHAR* lpsz) - { - #if (__GNUC__ < 3) // I'm not sure which precisely version should be put here - return lpsz ? std::string_char_traits::length(lpsz) : 0; - #else - return lpsz ? std::char_traits::length(lpsz) : 0; - #endif - - } - static char tl(char c) - { - return (char)std::tolower(c); - } - static char tu(char c) - { - return (char)std::toupper(c); - } -#endif - - - -public: - CZipString(){} - explicit CZipString (TCHAR ch, int nRepeat = 1):stdbs(nRepeat, ch){} - CZipString( const CZipString& stringSrc ) {assign(stringSrc);} - CZipString( const stdbs& stringSrc ) {assign(stringSrc);} - CZipString( LPCTSTR lpsz ){if (!lpsz) Empty(); else assign(lpsz);} - operator LPCTSTR() const{return c_str();} - - int GetLength() const {return (int) size();} - bool IsEmpty() const {return empty();} - void Empty() {erase(begin(), end());} - TCHAR GetAt (int iIndex) const{return at(iIndex);} - TCHAR operator[] (int iIndex) const{return at(iIndex);} - void SetAt( int nIndex, TCHAR ch ) {at(nIndex) = ch;} - LPTSTR GetBuffer(int nMinBufLength) - { - if ((int)size() < nMinBufLength) - resize(nMinBufLength); - return empty() ? const_cast(data()) : &(at(0)); - } - void ReleaseBuffer( int nNewLength = -1 ) { resize(nNewLength > -1 ? nNewLength : zslen(c_str()));} - void TrimLeft( TCHAR chTarget ) - { - TrimInternalL(find_first_not_of(chTarget)); - } - void TrimLeft( LPCTSTR lpszTargets ) - { - TrimInternalL(find_first_not_of(lpszTargets)); - } - void TrimRight( TCHAR chTarget ) - { - TrimInternalR(find_last_not_of(chTarget)); - } - void TrimRight( LPCTSTR lpszTargets ) - { - TrimInternalR(find_last_not_of(lpszTargets)); - } - void Format(LPCTSTR lpszFormat, ...) - { - va_list arguments; - va_start (arguments, lpszFormat); - TCHAR* pBuf = NULL; - int iCounter = 1, uTotal = 0; - do - { - int nLen = sizeof(TCHAR) * iCounter*1024; - pBuf = (TCHAR*)realloc((void*)pBuf, nLen); - if (!pBuf) - return; - uTotal = _vsntprintf(pBuf, nLen - 1, lpszFormat, arguments); - if (uTotal == -1 || (uTotal == nLen - 1) ) // for some implementations - { - pBuf[nLen - 1] = _T('\0'); - if (iCounter == 7) - break; - } - else - { - pBuf[uTotal] = _T('\0'); - break; - } - - } while (true); - - va_end (arguments); - *this = pBuf; - free(pBuf); - } - void Insert( int nIndex, LPCTSTR pstr ){insert(nIndex, pstr, zslen(pstr));} - void Insert( int nIndex, TCHAR ch ) {insert(nIndex, 1, ch);} - int Delete( int nIndex, int nCount = 1 ) - { - int iSize = (int) size(); - int iToDelete = iSize < nIndex + nCount ? iSize - nIndex : nCount; - if (iToDelete > 0) - { - erase(nIndex, iToDelete); - iSize -= iToDelete; - } - return iSize; - } - void MakeLower() - { - std::transform(begin(),end(),begin(),tl); - } - void MakeUpper() - { - std::transform(begin(),end(),begin(),tu); - } - void MakeReverse() - { - std::reverse(begin(), end()); - - } - CZipString Left( int nCount ) const { return substr(0, nCount);} - CZipString Right( int nCount) const - { - nCount = (int)size() < nCount ? (int)size() : nCount; - return substr(size() - nCount); - } - CZipString Mid( int nFirst ) const {return substr(nFirst);} - CZipString Mid( int nFirst, int nCount ) const {return substr(nFirst, nCount);} - int Collate( LPCTSTR lpsz ) const - { -#ifndef __GNUC__ - #ifdef _UNICODE - return wcscoll(c_str(), lpsz); - #else - return strcoll(c_str(), lpsz); - #endif -#else -// return compare(lpsz); - return strcoll(c_str(), lpsz); -#endif - - } - int CollateNoCase( LPCTSTR lpsz ) const - { - CZipString s1(c_str()), s2(lpsz); - s1.MakeLower(); - s2.MakeLower(); - return s1.Collate(s2); - } - int Compare( LPCTSTR lpsz ) const - { - return compare(lpsz); - } - int CompareNoCase( LPCTSTR lpsz ) const - { - CZipString s1(c_str()), s2(lpsz); - s1.MakeLower(); - s2.MakeLower(); - return s1.Compare(s2); - } - bool operator != (LPCTSTR lpsz) - { - return Compare(lpsz) != 0; - } - bool operator == (LPCTSTR lpsz) - { - return Compare(lpsz) == 0; - } - int Find( TCHAR ch, int nStart = 0) const - { - return (int) find(ch, nStart); - } - - int Find( LPCTSTR pstr, int nStart = 0) const - { - return (int) find(pstr, nStart); - } - - int Replace( TCHAR chOld, TCHAR chNew ) - { - int iCount = 0; - for (iterator it = begin(); it != end(); ++it) - if (*it == chOld) - { - *it = chNew; - iCount++; - } - return iCount; - } - - - - -}; - -/** - A poiter type to point to CZipString to Collate or CollateNoCase - or Compare or CompareNoCase -*/ -typedef int (CZipString::*ZIPSTRINGCOMPARE)( LPCTSTR ) const; - -/** - return a pointer to the function in CZipString structure, - used to compare elements depending on the arguments -*/ - ZIP_API ZIPSTRINGCOMPARE GetCZipStrCompFunc(bool bCaseSensitive, bool bCollate = true); - - -#if defined(_MSC_VER) && (_MSC_VER > 1100) - #pragma warning( pop) -#endif - - -#endif //__ZIPSTRING_H__ - diff --git a/harbour/contrib/hbziparch/zlib/deflate.h b/harbour/contrib/hbziparch/zlib/deflate.h new file mode 100644 index 0000000000..f3c464318a --- /dev/null +++ b/harbour/contrib/hbziparch/zlib/deflate.h @@ -0,0 +1,5 @@ +/* + * $Id$ + */ + +#include "zlib.h" diff --git a/harbour/contrib/hbziparch/zlib/zlib.h b/harbour/contrib/hbziparch/zlib/zlib.h new file mode 100644 index 0000000000..4b122606b1 --- /dev/null +++ b/harbour/contrib/hbziparch/zlib/zlib.h @@ -0,0 +1,94 @@ +/* + * $Id$ + */ + +/* NOTE: This is a stub to plug the Harbour ZLIB library of Harbour, + without the need to modify ZipArchive sources. Notice that + ZipArchive uses a modified ZLIB sources for large file support, + but this is available only in the commercial version of the + lib anyway. [vszakats] */ + +#include "hbzlib.h" + +//# define zarch_deflateInit deflateInit +# define zarch_deflateInit_ deflateInit_ +# define zarch_deflate deflate +# define zarch_deflateEnd deflateEnd +//# define zarch_deflateInit2 deflateInit2 +# define zarch_deflateInit2_ deflateInit2_ +# define zarch_deflateSetDictionary deflateSetDictionary +# define zarch_deflateCopy deflateCopy +# define zarch_deflateReset deflateReset +# define zarch_deflateParams deflateParams +# define zarch_deflateBound deflateBound +# define zarch_deflatePrime deflatePrime +# define zarch_deflateSetHeader deflateSetHeader +# define zarch_deflateTune deflateTune +//# define zarch_inflateInit inflateInit +//# define zarch_inflateInit2 inflateInit2 +# define zarch_inflateInit2_ inflateInit2_ +# define zarch_inflateInit_ inflateInit_ +# define zarch_inflate inflate +# define zarch_inflateEnd inflateEnd +# define zarch_inflateSetDictionary inflateSetDictionary +# define zarch_inflateSync inflateSync +# define zarch_inflateSyncPoint inflateSyncPoint +# define zarch_inflateCopy inflateCopy +# define zarch_inflateReset inflateReset +//# define zarch_inflateBackInit inflateBackInit +# define zarch_inflateBackInit_ inflateBackInit_ +# define zarch_inflateBack inflateBack +# define zarch_inflateBackEnd inflateBackEnd +# define zarch_inflatePrime inflatePrime +# define zarch_inflateGetHeader inflateGetHeader +# define zarch_compress compress +# define zarch_compress2 compress2 +# define zarch_compressBound compressBound +# define zarch_uncompress uncompress +# define zarch_adler32 adler32 +# define zarch_adler32_combine adler32_combine +# define zarch_crc32_combine crc32_combine +# define zarch_deflate_copyright deflate_copyright +# define zarch_inflate_copyright inflate_copyright +# define zarch_crc32 crc32 +# define zarch_get_crc_table get_crc_table +# define zarch_zError zError +# define zarch_z_stream z_stream +# define zarch_z_stream_s z_stream_s +# define zarch_alloc_func alloc_func +# define zarch_free_func free_func +# define zarch_in_func in_func +# define zarch_out_func out_func +# define zarch_Byte Byte +# define zarch_uInt uInt +# define zarch_uLong uLong +# define zarch_uLongLong uLongLong +# define zarch_Bytef Bytef +# define zarch_charf charf +# define zarch_intf intf +# define zarch_uIntf uIntf +# define zarch_uLongf uLongf +# define zarch_voidpf voidpf +# define zarch_voidp voidp +# define zarch_deflate_state deflate_state +# define zarch_deflate_slow deflate_slow +# define zarch_deflate_fast deflate_fast +# define zarch_deflate_stored deflate_stored +# define zarch_z_streamp z_streamp +# define zarch_deflate_rle deflate_rle +# define zarch_inflate_state inflate_state +# define zarch_inflate_fast inflate_fast +# define zarch_inflate_table inflate_table +# define zarch_updatewindow updatewindow +//# define zarch_inflate_mode inflate_mode +//# define zarch_send_bits send_bits +# define zarch_zlibVersion zlibVersion +# define zarch_zlibCompileFlags zlibCompileFlags +# define zarch_zError zError +# define zarch_tr_init _tr_init +# define zarch_tr_tally _tr_tally +# define zarch_tr_flush_block _tr_flush_block +# define zarch_tr_align _tr_align +# define zarch_tr_stored_block _tr_stored_block +# define zarch_dist_code _dist_code +# define zarch_length_code _length_code