Commit ef338166 by Tom Tromey Committed by Tom Tromey

* Imported zlib 1.2.3; merged local changes.

From-SVN: r104184
parent 3ec980b1
ChangeLog file for zlib ChangeLog file for zlib
Changes in 1.2.3 (18 July 2005)
- Apply security vulnerability fixes to contrib/infback9 as well
- Clean up some text files (carriage returns, trailing space)
- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
Changes in 1.2.2.4 (11 July 2005)
- Add inflatePrime() function for starting inflation at bit boundary
- Avoid some Visual C warnings in deflate.c
- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
compile
- Fix some spelling errors in comments [Betts]
- Correct inflateInit2() error return documentation in zlib.h
- Added zran.c example of compressed data random access to examples
directory, shows use of inflatePrime()
- Fix cast for assignments to strm->state in inflate.c and infback.c
- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
- Add cast in trees.c t avoid a warning [Oberhumer]
- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
- Update make_vms.com [Zinser]
- Initialize state->write in inflateReset() since copied in inflate_fast()
- Be more strict on incomplete code sets in inflate_table() and increase
ENOUGH and MAXD -- this repairs a possible security vulnerability for
invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for
discovering the vulnerability and providing test cases.
- Add ia64 support to configure for HP-UX [Smith]
- Add error return to gzread() for format or i/o error [Levin]
- Use malloc.h for OS/2 [Necasek]
Changes in 1.2.2.3 (27 May 2005)
- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
- Typecast fread() return values in gzio.c [Vollant]
- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
- Fix crc check bug in gzread() after gzungetc() [Heiner]
- Add the deflateTune() function to adjust internal compression parameters
- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
- Remove an incorrect assertion in examples/zpipe.c
- Add C++ wrapper in infback9.h [Donais]
- Fix bug in inflateCopy() when decoding fixed codes
- Note in zlib.h how much deflateSetDictionary() actually uses
- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
- Add gzdirect() function to indicate transparent reads
- Update contrib/minizip [Vollant]
- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
- Add casts in crc32.c to avoid warnings [Oberhumer]
- Add contrib/masmx64 [Vollant]
- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
Changes in 1.2.2.2 (30 December 2004)
- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
avoid implicit memcpy calls (portability for no-library compilation)
- Increase sprintf() buffer size in gzdopen() to allow for large numbers
- Add INFLATE_STRICT to check distances against zlib header
- Improve WinCE errno handling and comments [Chang]
- Remove comment about no gzip header processing in FAQ
- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
- Add updated make_vms.com [Coghlan], update README
- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
- Add FAQ entry and comments in deflate.c on uninitialized memory access
- Add Solaris 9 make options in configure [Gilbert]
- Allow strerror() usage in gzio.c for STDC
- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
- Use z_off_t for adler32_combine() and crc32_combine() lengths
- Make adler32() much faster for small len
- Use OS_CODE in deflate() default gzip header
Changes in 1.2.2.1 (31 October 2004)
- Allow inflateSetDictionary() call for raw inflate
- Fix inflate header crc check bug for file names and comments
- Add deflateSetHeader() and gz_header structure for custom gzip headers
- Add inflateGetheader() to retrieve gzip headers
- Add crc32_combine() and adler32_combine() functions
- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
- Use zstreamp consistently in zlib.h (inflate_back functions)
- Remove GUNZIP condition from definition of inflate_mode in inflate.h
and in contrib/inflate86/inffast.S [Truta, Anderson]
- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
- Update projects/README.projects and projects/visualc6 [Truta]
- Update win32/DLL_FAQ.txt [Truta]
- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
- Use a new algorithm for setting strm->data_type in trees.c [Truta]
- Do not define an exit() prototype in zutil.c unless DEBUG defined
- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
- Fix Darwin build version identification [Peterson]
Changes in 1.2.2 (3 October 2004)
- Update zlib.h comments on gzip in-memory processing
- Set adler to 1 in inflateReset() to support Java test suite [Walles]
- Add contrib/dotzlib [Ravn]
- Update win32/DLL_FAQ.txt [Truta]
- Update contrib/minizip [Vollant]
- Move contrib/visual-basic.txt to old/ [Truta]
- Fix assembler builds in projects/visualc6/ [Truta]
Changes in 1.2.1.2 (9 September 2004)
- Update INDEX file
- Fix trees.c to update strm->data_type (no one ever noticed!)
- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
- Add limited multitasking protection to DYNAMIC_CRC_TABLE
- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
- Don't declare strerror() under VMS [Mozilla]
- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
- Update contrib/ada [Anisimkov]
- Update contrib/minizip [Vollant]
- Fix configure to not hardcode directories for Darwin [Peterson]
- Fix gzio.c to not return error on empty files [Brown]
- Fix indentation; update version in contrib/delphi/ZLib.pas and
contrib/pascal/zlibpas.pas [Truta]
- Update mkasm.bat in contrib/masmx86 [Truta]
- Update contrib/untgz [Truta]
- Add projects/README.projects [Truta]
- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
- Update win32/DLL_FAQ.txt [Truta]
- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
- Remove an unnecessary assignment to curr in inftrees.c [Truta]
- Add OS/2 to exe builds in configure [Poltorak]
- Remove err dummy parameter in zlib.h [Kientzle]
Changes in 1.2.1.1 (9 January 2004)
- Update email address in README
- Several FAQ updates
- Fix a big fat bug in inftrees.c that prevented decoding valid
dynamic blocks with only literals and no distance codes --
Thanks to "Hot Emu" for the bug report and sample file
- Add a note to puff.c on no distance codes case.
Changes in 1.2.1 (17 November 2003) Changes in 1.2.1 (17 November 2003)
- Remove a tab in contrib/gzappend/gzappend.c - Remove a tab in contrib/gzappend/gzappend.c
- Update some interfaces in contrib for new zlib functions - Update some interfaces in contrib for new zlib functions
...@@ -407,7 +540,7 @@ Changes in 1.0.7 (20 Jan 1998) ...@@ -407,7 +540,7 @@ Changes in 1.0.7 (20 Jan 1998)
Changes in 1.0.6 (19 Jan 1998) Changes in 1.0.6 (19 Jan 1998)
- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and - add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
- Fix a deflate bug occuring only with compression level 0 (thanks to - Fix a deflate bug occurring only with compression level 0 (thanks to
Andy Buckler for finding this one). Andy Buckler for finding this one).
- In minigzip, pass transparently also the first byte for .Z files. - In minigzip, pass transparently also the first byte for .Z files.
- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() - return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
......
2005-06-14 Tom Tromey <tromey@redhat.com> 2005-06-14 Tom Tromey <tromey@redhat.com>
* Imported zlib 1.2.3; merged local changes.
2005-06-14 Tom Tromey <tromey@redhat.com>
PR libgcj/19877: PR libgcj/19877:
* configure, aclocal.m4, Makefile.in: Rebuilt. * configure, aclocal.m4, Makefile.in: Rebuilt.
......
...@@ -21,18 +21,18 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -21,18 +21,18 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
3. Where can I get a Visual Basic interface to zlib? 3. Where can I get a Visual Basic interface to zlib?
See See
* http://www.winimage.com/zLibDll/
* http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm * http://www.dogma.net/markn/articles/zlibtool/zlibtool.htm
* contrib/visual-basic.txt in the zlib distribution * contrib/visual-basic.txt in the zlib distribution
* win32/DLL_FAQ.txt in the zlib distribution
4. compress() returns Z_BUF_ERROR 4. compress() returns Z_BUF_ERROR.
Make sure that before the call of compress, the length of the compressed Make sure that before the call of compress, the length of the compressed
buffer is equal to the total size of the compressed buffer and not buffer is equal to the total size of the compressed buffer and not
zero. For Visual Basic, check that this parameter is passed by reference zero. For Visual Basic, check that this parameter is passed by reference
("as any"), not by value ("as long"). ("as any"), not by value ("as long").
5. deflate() or inflate() returns Z_BUF_ERROR 5. deflate() or inflate() returns Z_BUF_ERROR.
Before making the call, make sure that avail_in and avail_out are not Before making the call, make sure that avail_in and avail_out are not
zero. When setting the parameter flush equal to Z_FINISH, also make sure zero. When setting the parameter flush equal to Z_FINISH, also make sure
...@@ -47,8 +47,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -47,8 +47,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
It's in zlib.h for the moment, and Francis S. Lin has converted it to a It's in zlib.h for the moment, and Francis S. Lin has converted it to a
web page zlib.html. Volunteers to transform this to Unix-style man pages, web page zlib.html. Volunteers to transform this to Unix-style man pages,
please contact Jean-loup Gailly (jloup@gzip.org). Examples of zlib usage please contact us (zlib@gzip.org). Examples of zlib usage are in the files
are in the files example.c and minigzip.c. example.c and minigzip.c.
7. Why don't you use GNU autoconf or libtool or ...? 7. Why don't you use GNU autoconf or libtool or ...?
...@@ -77,7 +77,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -77,7 +77,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
11. Can zlib handle .zip archives? 11. Can zlib handle .zip archives?
See the directory contrib/minizip in the zlib distribution. Not by itself, no. See the directory contrib/minizip in the zlib
distribution.
12. Can zlib handle .Z files? 12. Can zlib handle .Z files?
...@@ -92,6 +93,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -92,6 +93,8 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
14. How do I install a shared zlib library on Unix? 14. How do I install a shared zlib library on Unix?
After the above, then:
make install make install
However, many flavors of Unix come with a shared zlib already installed. However, many flavors of Unix come with a shared zlib already installed.
...@@ -99,12 +102,31 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -99,12 +102,31 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
trying to install it, you may want to check if it's already there! If you trying to install it, you may want to check if it's already there! If you
can #include <zlib.h>, it's there. The -lz option will probably link to it. can #include <zlib.h>, it's there. The -lz option will probably link to it.
15. I have a question about OttoPDF 15. I have a question about OttoPDF.
We are not the authors of OttoPDF. The real author is on the OttoPDF web We are not the authors of OttoPDF. The real author is on the OttoPDF web
site Joel Hainley jhainley@myndkryme.com. site: Joel Hainley, jhainley@myndkryme.com.
16. Can zlib decode Flate data in an Adobe PDF file?
Yes. See http://www.fastio.com/ (ClibPDF), or http://www.pdflib.com/ .
To modify PDF forms, see http://sourceforge.net/projects/acroformtool/ .
17. Why am I getting this "register_frame_info not found" error on Solaris?
After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib
generates an error such as:
16. Why does gzip give an error on a file I make with compress/deflate? ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so:
symbol __register_frame_info: referenced symbol not found
The symbol __register_frame_info is not part of zlib, it is generated by
the C compiler (cc or gcc). You must recompile applications using zlib
which have this problem. This problem is specific to Solaris. See
http://www.sunfreeware.com for Solaris versions of zlib and applications
using zlib.
18. Why does gzip give an error on a file I make with compress/deflate?
The compress and deflate functions produce data in the zlib format, which The compress and deflate functions produce data in the zlib format, which
is different and incompatible with the gzip format. The gz* functions in is different and incompatible with the gzip format. The gz* functions in
...@@ -112,7 +134,7 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -112,7 +134,7 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
formats use the same compressed data format internally, but have different formats use the same compressed data format internally, but have different
headers and trailers around the compressed data. headers and trailers around the compressed data.
17. Ok, so why are there two different formats? 19. Ok, so why are there two different formats?
The gzip format was designed to retain the directory information about The gzip format was designed to retain the directory information about
a single file, such as the name and last modification date. The zlib a single file, such as the name and last modification date. The zlib
...@@ -120,20 +142,13 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -120,20 +142,13 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
channel applications, and has a much more compact header and trailer and channel applications, and has a much more compact header and trailer and
uses a faster integrity check than gzip. uses a faster integrity check than gzip.
18. Well that's nice, but how do I make a gzip file in memory? 20. Well that's nice, but how do I make a gzip file in memory?
You can request that deflate write the gzip format instead of the zlib You can request that deflate write the gzip format instead of the zlib
format using deflateInit2(). You can also request that inflate decode format using deflateInit2(). You can also request that inflate decode
the gzip format using inflateInit2(). Read zlib.h for more details. the gzip format using inflateInit2(). Read zlib.h for more details.
Note that you cannot specify special gzip header contents (e.g. a file 21. Is zlib thread-safe?
name or modification date), nor will inflate tell you what was in the
gzip header. If you need to customize the header or see what's in it,
you can use the raw deflate and inflate operations and the crc32()
function and roll your own gzip encoding and decoding. Read the gzip
RFC 1952 for details of the header and trailer format.
19. Is zlib thread-safe?
Yes. However any library routines that zlib uses and any application- Yes. However any library routines that zlib uses and any application-
provided memory allocation routines must also be thread-safe. zlib's gz* provided memory allocation routines must also be thread-safe. zlib's gz*
...@@ -144,15 +159,15 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -144,15 +159,15 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
Of course, you should only operate on any given zlib or gzip stream from a Of course, you should only operate on any given zlib or gzip stream from a
single thread at a time. single thread at a time.
20. Can I use zlib in my commercial application? 22. Can I use zlib in my commercial application?
Yes. Please read the license in zlib.h. Yes. Please read the license in zlib.h.
21. Is zlib under the GNU license? 23. Is zlib under the GNU license?
No. Please read the license in zlib.h. No. Please read the license in zlib.h.
22. The license says that altered source versions must be "plainly marked". So 24. The license says that altered source versions must be "plainly marked". So
what exactly do I need to do to meet that requirement? what exactly do I need to do to meet that requirement?
You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In
...@@ -175,24 +190,24 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -175,24 +190,24 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes
in zlib.h as you would for a full source distribution. in zlib.h as you would for a full source distribution.
23. Will zlib work on a big-endian or little-endian architecture, and can I 25. Will zlib work on a big-endian or little-endian architecture, and can I
exchange compressed data between them? exchange compressed data between them?
Yes and yes. Yes and yes.
24. Will zlib work on a 64-bit machine? 26. Will zlib work on a 64-bit machine?
It should. It has been tested on 64-bit machines, and has no dependence It should. It has been tested on 64-bit machines, and has no dependence
on any data types being limited to 32-bits in length. If you have any on any data types being limited to 32-bits in length. If you have any
difficulties, please provide a complete problem report to zlib@gzip.org difficulties, please provide a complete problem report to zlib@gzip.org
25. Will zlib decompress data from the PKWare Data Compression Library? 27. Will zlib decompress data from the PKWare Data Compression Library?
No. The PKWare DCL uses a completely different compressed data format No. The PKWare DCL uses a completely different compressed data format
than does PKZIP and zlib. However, you can look in zlib's contrib/blast than does PKZIP and zlib. However, you can look in zlib's contrib/blast
directory for a possible solution to your problem. directory for a possible solution to your problem.
26. Can I access data randomly in a compressed stream? 28. Can I access data randomly in a compressed stream?
No, not without some preparation. If when compressing you periodically No, not without some preparation. If when compressing you periodically
use Z_FULL_FLUSH, carefully write all the pending data at those points, use Z_FULL_FLUSH, carefully write all the pending data at those points,
...@@ -200,27 +215,27 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -200,27 +215,27 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
at those points. You have to be careful to not use Z_FULL_FLUSH too at those points. You have to be careful to not use Z_FULL_FLUSH too
often, since it can significantly degrade compression. often, since it can significantly degrade compression.
27. Does zlib work on MVS, OS/390, CICS, etc.? 29. Does zlib work on MVS, OS/390, CICS, etc.?
We don't know for sure. We have heard occasional reports of success on We don't know for sure. We have heard occasional reports of success on
these systems. If you do use it on one of these, please provide us with these systems. If you do use it on one of these, please provide us with
a report, instructions, and patches that we can reference when we get a report, instructions, and patches that we can reference when we get
these questions. Thanks. these questions. Thanks.
28. Is there some simpler, easier to read version of inflate I can look at 30. Is there some simpler, easier to read version of inflate I can look at
to understand the deflate format? to understand the deflate format?
First off, you should read RFC 1951. Second, yes. Look in zlib's First off, you should read RFC 1951. Second, yes. Look in zlib's
contrib/puff directory. contrib/puff directory.
29. Does zlib infringe on any patents? 31. Does zlib infringe on any patents?
As far as we know, no. In fact, that was originally the whole point behind As far as we know, no. In fact, that was originally the whole point behind
zlib. Look here for some more information: zlib. Look here for some more information:
http://www.gzip.org/#faq11 http://www.gzip.org/#faq11
30. Can zlib work with greater than 4 GB of data? 32. Can zlib work with greater than 4 GB of data?
Yes. inflate() and deflate() will process any amount of data correctly. Yes. inflate() and deflate() will process any amount of data correctly.
Each call of inflate() or deflate() is limited to input and output chunks Each call of inflate() or deflate() is limited to input and output chunks
...@@ -238,7 +253,7 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -238,7 +253,7 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
only if the compiler's "long" type is 32 bits. If the compiler's "long" only if the compiler's "long" type is 32 bits. If the compiler's "long"
type is 64 bits, then the limit is 16 exabytes. type is 64 bits, then the limit is 16 exabytes.
31. Does zlib have any security vulnerabilities? 33. Does zlib have any security vulnerabilities?
The only one that we are aware of is potentially in gzprintf(). If zlib The only one that we are aware of is potentially in gzprintf(). If zlib
is compiled to use sprintf() or vsprintf(), then there is no protection is compiled to use sprintf() or vsprintf(), then there is no protection
...@@ -258,35 +273,44 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -258,35 +273,44 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
Note that you should be using the most recent version of zlib. Versions Note that you should be using the most recent version of zlib. Versions
1.1.3 and before were subject to a double-free vulnerability. 1.1.3 and before were subject to a double-free vulnerability.
32. Is there a Java version of zlib? 34. Is there a Java version of zlib?
Probably what you want is to use zlib in Java. zlib is already included Probably what you want is to use zlib in Java. zlib is already included
as part of the Java SDK in the java.util.zip package. If you really want as part of the Java SDK in the java.util.zip package. If you really want
a version of zlib written in the Java language, look on the zlib home a version of zlib written in the Java language, look on the zlib home
page for links: http://www.zlib.org/ page for links: http://www.zlib.org/
33. I get this or that compiler or source-code scanner warning when I crank it 35. I get this or that compiler or source-code scanner warning when I crank it
up to maximally-pendantic. Can't you guys write proper code? up to maximally-pedantic. Can't you guys write proper code?
Many years ago, we gave up attempting to avoid warnings on every compiler Many years ago, we gave up attempting to avoid warnings on every compiler
in the universe. It just got to be a waste of time, and some compilers in the universe. It just got to be a waste of time, and some compilers
were downright silly. So now, we simply make sure that the code always were downright silly. So now, we simply make sure that the code always
works. works.
34. Will zlib read the (insert any ancient or arcane format here) compressed 36. Valgrind (or some similar memory access checker) says that deflate is
performing a conditional jump that depends on an uninitialized value.
Isn't that a bug?
No. That is intentional for performance reasons, and the output of
deflate is not affected. This only started showing up recently since
zlib 1.2.x uses malloc() by default for allocations, whereas earlier
versions used calloc(), which zeros out the allocated memory.
37. Will zlib read the (insert any ancient or arcane format here) compressed
data format? data format?
Probably not. Look in the comp.compression FAQ for pointers to various Probably not. Look in the comp.compression FAQ for pointers to various
formats and associated software. formats and associated software.
35. How can I encrypt/decrypt zip files with zlib? 38. How can I encrypt/decrypt zip files with zlib?
zlib doesn't support encryption. The original PKZIP encryption is very weak zlib doesn't support encryption. The original PKZIP encryption is very weak
and can be broken with freely available programs. To get strong encryption, and can be broken with freely available programs. To get strong encryption,
use gpg ( http://www.gnupg.org/ ) which already includes zlib compression. use GnuPG, http://www.gnupg.org/ , which already includes zlib compression.
For PKZIP compatible "encryption", look at http://www.info-zip.org/ For PKZIP compatible "encryption", look at http://www.info-zip.org/
36. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? 39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings?
"gzip" is the gzip format, and "deflate" is the zlib format. They should "gzip" is the gzip format, and "deflate" is the zlib format. They should
probably have called the second one "zlib" instead to avoid confusion probably have called the second one "zlib" instead to avoid confusion
...@@ -302,14 +326,14 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html ...@@ -302,14 +326,14 @@ The lastest zlib FAQ is at http://www.gzip.org/zlib/zlib_faq.html
Bottom line: use the gzip format for HTTP 1.1 encoding. Bottom line: use the gzip format for HTTP 1.1 encoding.
37. Does zlib support the new "Deflate64" format introduced by PKWare? 40. Does zlib support the new "Deflate64" format introduced by PKWare?
No. PKWare has apparently decided to keep that format proprietary, since No. PKWare has apparently decided to keep that format proprietary, since
they have not documented it as they have previous compression formats. they have not documented it as they have previous compression formats.
In any case, the compression improvements are so modest compared to other In any case, the compression improvements are so modest compared to other
more modern approaches, that it's not worth the effort to implement. more modern approaches, that it's not worth the effort to implement.
38. Can you please sign these lengthy legal documents and fax them back to us 41. Can you please sign these lengthy legal documents and fax them back to us
so that we can use your software in our product? so that we can use your software in our product?
No. Go away. Shoo. No. Go away. Shoo.
...@@ -8,9 +8,12 @@ algorithm.txt description of the (de)compression algorithm ...@@ -8,9 +8,12 @@ algorithm.txt description of the (de)compression algorithm
configure configure script for Unix configure configure script for Unix
zconf.in.h template for zconf.h (used by configure) zconf.in.h template for zconf.h (used by configure)
amiga/ makefiles for Amiga SAS C
as400/ makefiles for IBM AS/400
msdos/ makefiles for MSDOS msdos/ makefiles for MSDOS
old/ makefiles for various architectures and zlib documentation old/ makefiles for various architectures and zlib documentation
files that have not yet been updated for zlib 1.2.x files that have not yet been updated for zlib 1.2.x
projects/ projects for various Integrated Development Environments
qnx/ makefiles for QNX qnx/ makefiles for QNX
win32/ makefiles for Windows win32/ makefiles for Windows
......
...@@ -3,7 +3,7 @@ shipped with GCC as convenience. ...@@ -3,7 +3,7 @@ shipped with GCC as convenience.
ZLIB DATA COMPRESSION LIBRARY ZLIB DATA COMPRESSION LIBRARY
zlib 1.2.1 is a general purpose data compression library. All the code is zlib 1.2.3 is a general purpose data compression library. All the code is
thread safe. The data format used by the zlib library is described by RFCs thread safe. The data format used by the zlib library is described by RFCs
(Request for Comments) 1950 to 1952 in the files (Request for Comments) 1950 to 1952 in the files
http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format) http://www.ietf.org/rfc/rfc1950.txt (zlib format), rfc1951.txt (deflate format)
...@@ -19,9 +19,8 @@ minigzip.c. ...@@ -19,9 +19,8 @@ minigzip.c.
To compile all files and run the test program, follow the instructions given at To compile all files and run the test program, follow the instructions given at
the top of Makefile. In short "make test; make install" should work for most the top of Makefile. In short "make test; make install" should work for most
machines. For Unix: "./configure; make test; make install" For MSDOS, use one machines. For Unix: "./configure; make test; make install". For MSDOS, use one
of the special makefiles such as Makefile.msc. For VMS, use Make_vms.com or of the special makefiles such as Makefile.msc. For VMS, use make_vms.com.
descrip.mms.
Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
<info@winimage.com> for the Windows DLL version. The zlib home page is <info@winimage.com> for the Windows DLL version. The zlib home page is
...@@ -37,7 +36,7 @@ Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997 ...@@ -37,7 +36,7 @@ Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997
issue of Dr. Dobb's Journal; a copy of the article is available in issue of Dr. Dobb's Journal; a copy of the article is available in
http://dogma.net/markn/articles/zlibtool/zlibtool.htm http://dogma.net/markn/articles/zlibtool/zlibtool.htm
The changes made in version 1.2.1 are documented in the file ChangeLog. The changes made in version 1.2.3 are documented in the file ChangeLog.
Unsupported third party contributions are provided in directory "contrib". Unsupported third party contributions are provided in directory "contrib".
...@@ -49,7 +48,7 @@ A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the ...@@ -49,7 +48,7 @@ A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is in the
CPAN (Comprehensive Perl Archive Network) sites CPAN (Comprehensive Perl Archive Network) sites
http://www.cpan.org/modules/by-module/Compress/ http://www.cpan.org/modules/by-module/Compress/
A Python interface to zlib written by A.M. Kuchling <amk@magnet.com> is A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
available in Python 1.5 and later versions, see available in Python 1.5 and later versions, see
http://www.python.org/doc/lib/module-zlib.html http://www.python.org/doc/lib/module-zlib.html
...@@ -96,7 +95,7 @@ Acknowledgments: ...@@ -96,7 +95,7 @@ Acknowledgments:
Copyright notice: Copyright notice:
(C) 1995-2003 Jean-loup Gailly and Mark Adler (C) 1995-2004 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages warranty. In no event will the authors be held liable for any damages
......
/* adler32.c -- compute the Adler-32 checksum of a data stream /* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2004 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -12,12 +12,13 @@ ...@@ -12,12 +12,13 @@
#define NMAX 5552 #define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8); #define DO16(buf) DO8(buf,0); DO8(buf,8);
/* use NO_DIVIDE if your processor does not do division in hardware */
#ifdef NO_DIVIDE #ifdef NO_DIVIDE
# define MOD(a) \ # define MOD(a) \
do { \ do { \
...@@ -39,8 +40,17 @@ ...@@ -39,8 +40,17 @@
if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \ if (a >= BASE) a -= BASE; \
} while (0) } while (0)
# define MOD4(a) \
do { \
if (a >= (BASE << 4)) a -= (BASE << 4); \
if (a >= (BASE << 3)) a -= (BASE << 3); \
if (a >= (BASE << 2)) a -= (BASE << 2); \
if (a >= (BASE << 1)) a -= (BASE << 1); \
if (a >= BASE) a -= BASE; \
} while (0)
#else #else
# define MOD(a) a %= BASE # define MOD(a) a %= BASE
# define MOD4(a) a %= BASE
#endif #endif
/* ========================================================================= */ /* ========================================================================= */
...@@ -49,26 +59,91 @@ uLong ZEXPORT adler32(adler, buf, len) ...@@ -49,26 +59,91 @@ uLong ZEXPORT adler32(adler, buf, len)
const Bytef *buf; const Bytef *buf;
uInt len; uInt len;
{ {
unsigned long s1 = adler & 0xffff; unsigned long sum2;
unsigned long s2 = (adler >> 16) & 0xffff; unsigned n;
int k;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
if (buf == Z_NULL) return 1L; /* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == Z_NULL)
return 1L;
while (len > 0) { /* in case short lengths are provided, keep it somewhat fast */
k = len < NMAX ? (int)len : NMAX; if (len < 16) {
len -= k; while (len--) {
while (k >= 16) { adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD4(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf); DO16(buf);
buf += 16; buf += 16;
k -= 16;
} }
if (k != 0) do { while (len--) {
s1 += *buf++; adler += *buf++;
s2 += s1; sum2 += adler;
} while (--k); }
MOD(s1); MOD(adler);
MOD(s2); MOD(sum2);
} }
return (s2 << 16) | s1;
/* return recombined sums */
return adler | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32_combine(adler1, adler2, len2)
uLong adler1;
uLong adler2;
z_off_t len2;
{
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* the derivation of this formula is left as an exercise for the reader */
rem = (unsigned)(len2 % BASE);
sum1 = adler1 & 0xffff;
sum2 = rem * sum1;
MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 > BASE) sum1 -= BASE;
if (sum1 > BASE) sum1 -= BASE;
if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
if (sum2 > BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
} }
...@@ -23,7 +23,7 @@ all: SCOPTIONS example minigzip ...@@ -23,7 +23,7 @@ all: SCOPTIONS example minigzip
check: test check: test
test: all test: all
example example
echo hello world | minigzip | minigzip -d echo hello world | minigzip | minigzip -d
install: z.lib install: z.lib
copy clone zlib.h zconf.h INCLUDE: copy clone zlib.h zconf.h INCLUDE:
......
/* compress.c -- compress a memory buffer /* compress.c -- compress a memory buffer
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2003 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
......
...@@ -19,8 +19,8 @@ blast/ by Mark Adler <madler@alumni.caltech.edu> ...@@ -19,8 +19,8 @@ blast/ by Mark Adler <madler@alumni.caltech.edu>
delphi/ by Cosmin Truta <cosmint@cs.ubbcluj.ro> delphi/ by Cosmin Truta <cosmint@cs.ubbcluj.ro>
Support for Delphi and C++ Builder Support for Delphi and C++ Builder
gzappend/ by Mark Adler <madler@alumni.caltech.edu> dotzlib/ by Henrik Ravn <henrik@ravn.com>
append to a gzip file -- illustrates the use of Z_BLOCK Support for Microsoft .Net and Visual C++ .Net
infback9/ by Mark Adler <madler@alumni.caltech.edu> infback9/ by Mark Adler <madler@alumni.caltech.edu>
Unsupported diffs to infback to decode the deflate64 format Unsupported diffs to infback to decode the deflate64 format
...@@ -42,6 +42,10 @@ masm686/ by Dan Higdon <hdan@kinesoft.com> ...@@ -42,6 +42,10 @@ masm686/ by Dan Higdon <hdan@kinesoft.com>
and Chuck Walbourn <chuckw@kinesoft.com> and Chuck Walbourn <chuckw@kinesoft.com>
asm code for Pentium Pro/PII, using the MASM syntax asm code for Pentium Pro/PII, using the MASM syntax
masmx64/ by Gilles Vollant <info@winimage.com>
x86 64-bit (AMD64 and Intel EM64t) code for x64 assembler to
replace longest_match() and inflate_fast()
masmx86/ by Gilles Vollant <info@winimage.com> masmx86/ by Gilles Vollant <info@winimage.com>
x86 asm code to replace longest_match() and inflate_fast(), x86 asm code to replace longest_match() and inflate_fast(),
for Visual C++ and MASM for Visual C++ and MASM
...@@ -60,11 +64,8 @@ puff/ by Mark Adler <madler@alumni.caltech.edu> ...@@ -60,11 +64,8 @@ puff/ by Mark Adler <madler@alumni.caltech.edu>
testzlib/ by Gilles Vollant <info@winimage.com> testzlib/ by Gilles Vollant <info@winimage.com>
Example of the use of zlib Example of the use of zlib
untgz/ by "Pedro A. Aranda Guti\irrez" <paag@tid.es> untgz/ by Pedro A. Aranda Gutierrez <paag@tid.es>
A very simple tar.gz file extractor using zlib A very simple tar.gz file extractor using zlib
visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
How to use compress(), uncompress() and the gz* functions from VB
vstudio/ by Gilles Vollant <info@winimage.com> vstudio/ by Gilles Vollant <info@winimage.com>
Building zlib with Visual Studio .NET Building a minizip-enhanced zlib with Microsoft Visual Studio
...@@ -45,19 +45,29 @@ ...@@ -45,19 +45,29 @@
* program to crash horribly, without so much as a warning at * program to crash horribly, without so much as a warning at
* compile time. Sigh.) * compile time. Sigh.)
*/ */
#define dsWSize 36
#define dsWMask 44 /* All the +zlib1222add offsets are due to the addition of fields
#define dsWindow 48 * in zlib in the deflate_state structure since the asm code was first written
#define dsPrev 56 * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").
#define dsMatchLen 88 * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").
#define dsPrevMatch 92 * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").
#define dsStrStart 100 */
#define dsMatchStart 104
#define dsLookahead 108 #define zlib1222add (8)
#define dsPrevLen 112
#define dsMaxChainLen 116 #define dsWSize (36+zlib1222add)
#define dsGoodMatch 132 #define dsWMask (44+zlib1222add)
#define dsNiceMatch 136 #define dsWindow (48+zlib1222add)
#define dsPrev (56+zlib1222add)
#define dsMatchLen (88+zlib1222add)
#define dsPrevMatch (92+zlib1222add)
#define dsStrStart (100+zlib1222add)
#define dsMatchStart (104+zlib1222add)
#define dsLookahead (108+zlib1222add)
#define dsPrevLen (112+zlib1222add)
#define dsMaxChainLen (116+zlib1222add)
#define dsGoodMatch (132+zlib1222add)
#define dsNiceMatch (136+zlib1222add)
.file "match.S" .file "match.S"
......
...@@ -38,26 +38,28 @@ ...@@ -38,26 +38,28 @@
#define deflatestate 56 /* the function arguments */ #define deflatestate 56 /* the function arguments */
#define curmatch 60 #define curmatch 60
/* Offsets for fields in the deflate_state structure. These numbers /* All the +zlib1222add offsets are due to the addition of fields
* are calculated from the definition of deflate_state, with the * in zlib in the deflate_state structure since the asm code was first written
* assumption that the compiler will dword-align the fields. (Thus, * (if you compile with zlib 1.0.4 or older, use "zlib1222add equ (-4)").
* changing the definition of deflate_state could easily cause this * (if you compile with zlib between 1.0.5 and 1.2.2.1, use "zlib1222add equ 0").
* program to crash horribly, without so much as a warning at * if you compile with zlib 1.2.2.2 or later , use "zlib1222add equ 8").
* compile time. Sigh.)
*/ */
#define dsWSize 36
#define dsWMask 44 #define zlib1222add (8)
#define dsWindow 48
#define dsPrev 56 #define dsWSize (36+zlib1222add)
#define dsMatchLen 88 #define dsWMask (44+zlib1222add)
#define dsPrevMatch 92 #define dsWindow (48+zlib1222add)
#define dsStrStart 100 #define dsPrev (56+zlib1222add)
#define dsMatchStart 104 #define dsMatchLen (88+zlib1222add)
#define dsLookahead 108 #define dsPrevMatch (92+zlib1222add)
#define dsPrevLen 112 #define dsStrStart (100+zlib1222add)
#define dsMaxChainLen 116 #define dsMatchStart (104+zlib1222add)
#define dsGoodMatch 132 #define dsLookahead (108+zlib1222add)
#define dsNiceMatch 136 #define dsPrevLen (112+zlib1222add)
#define dsMaxChainLen (116+zlib1222add)
#define dsGoodMatch (132+zlib1222add)
#define dsNiceMatch (136+zlib1222add)
.file "match.S" .file "match.S"
......
/* gzappend -- command to append to a gzip file
Copyright (C) 2003 Mark Adler, all rights reserved
version 1.1, 4 Nov 2003
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Mark Adler madler@alumni.caltech.edu
*/
/*
* Change history:
*
* 1.0 19 Oct 2003 - First version
* 1.1 4 Nov 2003 - Expand and clarify some comments and notes
* - Add version and copyright to help
* - Send help to stdout instead of stderr
* - Add some preemptive typecasts
* - Add L to constants in lseek() calls
* - Remove some debugging information in error messages
* - Use new data_type definition for zlib 1.2.1
* - Simplfy and unify file operations
* - Finish off gzip file in gztack()
* - Use deflatePrime() instead of adding empty blocks
* - Keep gzip file clean on appended file read errors
* - Use in-place rotate instead of auxiliary buffer
* (Why you ask? Because it was fun to write!)
*/
/*
gzappend takes a gzip file and appends to it, compressing files from the
command line or data from stdin. The gzip file is written to directly, to
avoid copying that file, in case it's large. Note that this results in the
unfriendly behavior that if gzappend fails, the gzip file is corrupted.
This program was written to illustrate the use of the new Z_BLOCK option of
zlib 1.2.1's inflate() function. This option returns from inflate() at each
block boundary to facilitate locating and modifying the last block bit at
the start of the final deflate block. Also whether using Z_BLOCK or not,
another required feature of zlib 1.2.1 is that inflate() now provides the
number of unusued bits in the last input byte used. gzappend will not work
with versions of zlib earlier than 1.2.1.
gzappend first decompresses the gzip file internally, discarding all but
the last 32K of uncompressed data, and noting the location of the last block
bit and the number of unused bits in the last byte of the compressed data.
The gzip trailer containing the CRC-32 and length of the uncompressed data
is verified. This trailer will be later overwritten.
Then the last block bit is cleared by seeking back in the file and rewriting
the byte that contains it. Seeking forward, the last byte of the compressed
data is saved along with the number of unused bits to initialize deflate.
A deflate process is initialized, using the last 32K of the uncompressed
data from the gzip file to initialize the dictionary. If the total
uncompressed data was less than 32K, then all of it is used to initialize
the dictionary. The deflate output bit buffer is also initialized with the
last bits from the original deflate stream. From here on, the data to
append is simply compressed using deflate, and written to the gzip file.
When that is complete, the new CRC-32 and uncompressed length are written
as the trailer of the gzip file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include "zlib.h"
#define local static
#define LGCHUNK 14
#define CHUNK (1U << LGCHUNK)
#define DSIZE 32768U
/* print an error message and terminate with extreme prejudice */
local void bye(char *msg1, char *msg2)
{
fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2);
exit(1);
}
/* return the greatest common divisor of a and b using Euclid's algorithm,
modified to be fast when one argument much greater than the other, and
coded to avoid unnecessary swapping */
local unsigned gcd(unsigned a, unsigned b)
{
unsigned c;
while (a && b)
if (a > b) {
c = b;
while (a - c >= c)
c <<= 1;
a -= c;
}
else {
c = a;
while (b - c >= c)
c <<= 1;
b -= c;
}
return a + b;
}
/* rotate list[0..len-1] left by rot positions, in place */
local void rotate(unsigned char *list, unsigned len, unsigned rot)
{
unsigned char tmp;
unsigned cycles;
unsigned char *start, *last, *to, *from;
/* normalize rot and handle degenerate cases */
if (len < 2) return;
if (rot >= len) rot %= len;
if (rot == 0) return;
/* pointer to last entry in list */
last = list + (len - 1);
/* do simple left shift by one */
if (rot == 1) {
tmp = *list;
memcpy(list, list + 1, len - 1);
*last = tmp;
return;
}
/* do simple right shift by one */
if (rot == len - 1) {
tmp = *last;
memmove(list + 1, list, len - 1);
*list = tmp;
return;
}
/* otherwise do rotate as a set of cycles in place */
cycles = gcd(len, rot); /* number of cycles */
do {
start = from = list + cycles; /* start index is arbitrary */
tmp = *from; /* save entry to be overwritten */
for (;;) {
to = from; /* next step in cycle */
from += rot; /* go right rot positions */
if (from > last) from -= len; /* (pointer better not wrap) */
if (from == start) break; /* all but one shifted */
*to = *from; /* shift left */
}
*to = tmp; /* complete the circle */
} while (--cycles);
}
/* structure for gzip file read operations */
typedef struct {
int fd; /* file descriptor */
int size; /* 1 << size is bytes in buf */
unsigned left; /* bytes available at next */
unsigned char *buf; /* buffer */
unsigned char *next; /* next byte in buffer */
char *name; /* file name for error messages */
} file;
/* reload buffer */
local int readin(file *in)
{
int len;
len = read(in->fd, in->buf, 1 << in->size);
if (len == -1) bye("error reading ", in->name);
in->left = (unsigned)len;
in->next = in->buf;
return len;
}
/* read from file in, exit if end-of-file */
local int readmore(file *in)
{
if (readin(in) == 0) bye("unexpected end of ", in->name);
return 0;
}
#define read1(in) (in->left == 0 ? readmore(in) : 0, \
in->left--, *(in->next)++)
/* skip over n bytes of in */
local void skip(file *in, unsigned n)
{
unsigned bypass;
if (n > in->left) {
n -= in->left;
bypass = n & ~((1U << in->size) - 1);
if (bypass) {
if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1)
bye("seeking ", in->name);
n -= bypass;
}
readmore(in);
if (n > in->left)
bye("unexpected end of ", in->name);
}
in->left -= n;
in->next += n;
}
/* read a four-byte unsigned integer, little-endian, from in */
unsigned long read4(file *in)
{
unsigned long val;
val = read1(in);
val += (unsigned)read1(in) << 8;
val += (unsigned long)read1(in) << 16;
val += (unsigned long)read1(in) << 24;
return val;
}
/* skip over gzip header */
local void gzheader(file *in)
{
int flags;
unsigned n;
if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file");
if (read1(in) != 8) bye("unknown compression method in", in->name);
flags = read1(in);
if (flags & 0xe0) bye("unknown header flags set in", in->name);
skip(in, 6);
if (flags & 4) {
n = read1(in);
n += (unsigned)(read1(in)) << 8;
skip(in, n);
}
if (flags & 8) while (read1(in) != 0) ;
if (flags & 16) while (read1(in) != 0) ;
if (flags & 2) skip(in, 2);
}
/* decompress gzip file "name", return strm with a deflate stream ready to
continue compression of the data in the gzip file, and return a file
descriptor pointing to where to write the compressed data -- the deflate
stream is initialized to compress using level "level" */
local int gzscan(char *name, z_stream *strm, int level)
{
int ret, lastbit, left, full;
unsigned have;
unsigned long crc, tot;
unsigned char *window;
off_t lastoff, end;
file gz;
/* open gzip file */
gz.name = name;
gz.fd = open(name, O_RDWR, 0);
if (gz.fd == -1) bye("cannot open ", name);
gz.buf = malloc(CHUNK);
if (gz.buf == NULL) bye("out of memory", "");
gz.size = LGCHUNK;
gz.left = 0;
/* skip gzip header */
gzheader(&gz);
/* prepare to decompress */
window = malloc(DSIZE);
if (window == NULL) bye("out of memory", "");
strm->zalloc = Z_NULL;
strm->zfree = Z_NULL;
strm->opaque = Z_NULL;
ret = inflateInit2(strm, -15);
if (ret != Z_OK) bye("out of memory", " or library mismatch");
/* decompress the deflate stream, saving append information */
lastbit = 0;
lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left;
left = 0;
strm->avail_in = gz.left;
strm->next_in = gz.next;
crc = crc32(0L, Z_NULL, 0);
have = full = 0;
do {
/* if needed, get more input */
if (strm->avail_in == 0) {
readmore(&gz);
strm->avail_in = gz.left;
strm->next_in = gz.next;
}
/* set up output to next available section of sliding window */
strm->avail_out = DSIZE - have;
strm->next_out = window + have;
/* inflate and check for errors */
ret = inflate(strm, Z_BLOCK);
if (ret == Z_STREAM_ERROR) bye("internal stream error!", "");
if (ret == Z_MEM_ERROR) bye("out of memory", "");
if (ret == Z_DATA_ERROR)
bye("invalid compressed data--format violated in", name);
/* update crc and sliding window pointer */
crc = crc32(crc, window + have, DSIZE - have - strm->avail_out);
if (strm->avail_out)
have = DSIZE - strm->avail_out;
else {
have = 0;
full = 1;
}
/* process end of block */
if (strm->data_type & 128) {
if (strm->data_type & 64)
left = strm->data_type & 0x1f;
else {
lastbit = strm->data_type & 0x1f;
lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in;
}
}
} while (ret != Z_STREAM_END);
inflateEnd(strm);
gz.left = strm->avail_in;
gz.next = strm->next_in;
/* save the location of the end of the compressed data */
end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left;
/* check gzip trailer and save total for deflate */
if (crc != read4(&gz))
bye("invalid compressed data--crc mismatch in ", name);
tot = strm->total_out;
if ((tot & 0xffffffffUL) != read4(&gz))
bye("invalid compressed data--length mismatch in", name);
/* if not at end of file, warn */
if (gz.left || readin(&gz))
fprintf(stderr,
"gzappend warning: junk at end of gzip file overwritten\n");
/* clear last block bit */
lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET);
if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name);
*gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7)));
lseek(gz.fd, -1L, SEEK_CUR);
if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name);
/* if window wrapped, build dictionary from window by rotating */
if (full) {
rotate(window, DSIZE, have);
have = DSIZE;
}
/* set up deflate stream with window, crc, total_in, and leftover bits */
ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK) bye("out of memory", "");
deflateSetDictionary(strm, window, have);
strm->adler = crc;
strm->total_in = tot;
if (left) {
lseek(gz.fd, --end, SEEK_SET);
if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name);
deflatePrime(strm, 8 - left, *gz.buf);
}
lseek(gz.fd, end, SEEK_SET);
/* clean up and return */
free(window);
free(gz.buf);
return gz.fd;
}
/* append file "name" to gzip file gd using deflate stream strm -- if last
is true, then finish off the deflate stream at the end */
local void gztack(char *name, int gd, z_stream *strm, int last)
{
int fd, len, ret;
unsigned left;
unsigned char *in, *out;
/* open file to compress and append */
fd = 0;
if (name != NULL) {
fd = open(name, O_RDONLY, 0);
if (fd == -1)
fprintf(stderr, "gzappend warning: %s not found, skipping ...\n",
name);
}
/* allocate buffers */
in = fd == -1 ? NULL : malloc(CHUNK);
out = malloc(CHUNK);
if (out == NULL) bye("out of memory", "");
/* compress input file and append to gzip file */
do {
/* get more input */
len = fd == -1 ? 0 : read(fd, in, CHUNK);
if (len == -1) {
fprintf(stderr,
"gzappend warning: error reading %s, skipping rest ...\n",
name);
len = 0;
}
strm->avail_in = (unsigned)len;
strm->next_in = in;
if (len) strm->adler = crc32(strm->adler, in, (unsigned)len);
/* compress and write all available output */
do {
strm->avail_out = CHUNK;
strm->next_out = out;
ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH);
left = CHUNK - strm->avail_out;
while (left) {
len = write(gd, out + CHUNK - strm->avail_out - left, left);
if (len == -1) bye("writing gzip file", "");
left -= (unsigned)len;
}
} while (strm->avail_out == 0 && ret != Z_STREAM_END);
} while (len != 0);
/* write trailer after last entry */
if (last) {
deflateEnd(strm);
out[0] = (unsigned char)(strm->adler);
out[1] = (unsigned char)(strm->adler >> 8);
out[2] = (unsigned char)(strm->adler >> 16);
out[3] = (unsigned char)(strm->adler >> 24);
out[4] = (unsigned char)(strm->total_in);
out[5] = (unsigned char)(strm->total_in >> 8);
out[6] = (unsigned char)(strm->total_in >> 16);
out[7] = (unsigned char)(strm->total_in >> 24);
len = 8;
do {
ret = write(gd, out + 8 - len, len);
if (ret == -1) bye("writing gzip file", "");
len -= ret;
} while (len);
close(gd);
}
/* clean up and return */
free(out);
if (in != NULL) free(in);
if (fd > 0) close(fd);
}
/* process the compression level option if present, scan the gzip file, and
append the specified files, or append the data from stdin if no other file
names are provided on the command line -- the gzip file must be writable
and seekable */
int main(int argc, char **argv)
{
int gd, level;
z_stream strm;
/* ignore command name */
argv++;
/* provide usage if no arguments */
if (*argv == NULL) {
printf("gzappend 1.1 (4 Nov 2003) Copyright (C) 2003 Mark Adler\n");
printf(
"usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n");
return 0;
}
/* set compression level */
level = Z_DEFAULT_COMPRESSION;
if (argv[0][0] == '-') {
if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0)
bye("invalid compression level", "");
level = argv[0][1] - '0';
if (*++argv == NULL) bye("no gzip file name after options", "");
}
/* prepare to append to gzip file */
gd = gzscan(*argv++, &strm, level);
/* append files on command line, or from stdin if none */
if (*argv == NULL)
gztack(NULL, gd, &strm, 1);
else
do {
gztack(*argv, gd, &strm, argv[1] == NULL);
} while (*++argv != NULL);
return 0;
}
Change in 1.01e (12 feb 05)
- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter)
- Fix possible memory leak in unzip.c (Zoran Stevanovic)
Change in 1.01b (20 may 04)
- Integrate patch from Debian package (submited by Mark Brown)
- Add tools mztools from Xavier Roche
Change in 1.01 (8 may 04)
- fix buffer overrun risk in unzip.c (Xavier Roche)
- fix a minor buffer insecurity in minizip.c (Mike Whittaker)
Change in 1.00: (10 sept 03) Change in 1.00: (10 sept 03)
- rename to 1.00 - rename to 1.00
- cosmetic code change - cosmetic code change
......
/*
miniunz.c
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
...@@ -27,7 +35,7 @@ ...@@ -27,7 +35,7 @@
mini unzip, demo of unzip package mini unzip, demo of unzip package
usage : usage :
Usage : miniunz [-exvlo] file.zip [file_to_extract] Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
if it exists if it exists
...@@ -140,17 +148,18 @@ int makedir (newdir) ...@@ -140,17 +148,18 @@ int makedir (newdir)
void do_banner() void do_banner()
{ {
printf("MiniUnz 1.00, demo of zLib + Unz package written by Gilles Vollant\n"); printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
} }
void do_help() void do_help()
{ {
printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.]\n\n" \ printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
" -e Extract without pathname (junk paths)\n" \ " -e Extract without pathname (junk paths)\n" \
" -x Extract with pathname\n" \ " -x Extract with pathname\n" \
" -v list files\n" \ " -v list files\n" \
" -l list files\n" \ " -l list files\n" \
" -d directory to extract into\n" \
" -o overwrite files without prompting\n" \ " -o overwrite files without prompting\n" \
" -p extract crypted file using password\n\n"); " -p extract crypted file using password\n\n");
} }
...@@ -304,8 +313,14 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password) ...@@ -304,8 +313,14 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
do do
{ {
char answer[128]; char answer[128];
printf("The file %s exist. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); int ret;
scanf("%1s",answer);
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ; rep = answer[0] ;
if ((rep>='a') && (rep<='z')) if ((rep>='a') && (rep<='z'))
rep -= 0x20; rep -= 0x20;
...@@ -459,6 +474,8 @@ int main(argc,argv) ...@@ -459,6 +474,8 @@ int main(argc,argv)
int opt_do_extract=1; int opt_do_extract=1;
int opt_do_extract_withoutpath=0; int opt_do_extract_withoutpath=0;
int opt_overwrite=0; int opt_overwrite=0;
int opt_extractdir=0;
const char *dirname=NULL;
unzFile uf=NULL; unzFile uf=NULL;
do_banner(); do_banner();
...@@ -488,6 +505,12 @@ int main(argc,argv) ...@@ -488,6 +505,12 @@ int main(argc,argv)
opt_do_extract = opt_do_extract_withoutpath = 1; opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O')) if ((c=='o') || (c=='O'))
opt_overwrite=1; opt_overwrite=1;
if ((c=='d') || (c=='D'))
{
opt_extractdir=1;
dirname=argv[i+1];
}
if (((c=='p') || (c=='P')) && (i+1<argc)) if (((c=='p') || (c=='P')) && (i+1<argc))
{ {
password=argv[i+1]; password=argv[i+1];
...@@ -499,7 +522,7 @@ int main(argc,argv) ...@@ -499,7 +522,7 @@ int main(argc,argv)
{ {
if (zipfilename == NULL) if (zipfilename == NULL)
zipfilename = argv[i]; zipfilename = argv[i];
else if (filename_to_extract==NULL) else if ((filename_to_extract==NULL) && (!opt_extractdir))
filename_to_extract = argv[i] ; filename_to_extract = argv[i] ;
} }
} }
...@@ -544,6 +567,12 @@ int main(argc,argv) ...@@ -544,6 +567,12 @@ int main(argc,argv)
return do_list(uf); return do_list(uf);
else if (opt_do_extract==1) else if (opt_do_extract==1)
{ {
if (opt_extractdir && chdir(dirname))
{
printf("Error changing into %s, aborting\n", dirname);
exit(-1);
}
if (filename_to_extract == NULL) if (filename_to_extract == NULL)
return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password); return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password);
else else
......
/*
minizip.c
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
...@@ -53,8 +60,8 @@ uLong filetime(f, tmzip, dt) ...@@ -53,8 +60,8 @@ uLong filetime(f, tmzip, dt)
#else #else
#ifdef unix #ifdef unix
uLong filetime(f, tmzip, dt) uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */ char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */ tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */ uLong *dt; /* dostime */
{ {
int ret=0; int ret=0;
...@@ -66,6 +73,8 @@ uLong filetime(f, tmzip, dt) ...@@ -66,6 +73,8 @@ uLong filetime(f, tmzip, dt)
{ {
char name[MAXFILENAME+1]; char name[MAXFILENAME+1];
int len = strlen(f); int len = strlen(f);
if (len > MAXFILENAME)
len = MAXFILENAME;
strncpy(name, f,MAXFILENAME-1); strncpy(name, f,MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */ /* strncpy doesnt append the trailing NULL, of the string is too long. */
...@@ -120,7 +129,7 @@ int check_exist_file(filename) ...@@ -120,7 +129,7 @@ int check_exist_file(filename)
void do_banner() void do_banner()
{ {
printf("MiniZip 1.00, demo of zLib + Zip package written by Gilles Vollant\n"); printf("MiniZip 1.01b, demo of zLib + Zip package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n"); printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
} }
...@@ -269,8 +278,13 @@ int main(argc,argv) ...@@ -269,8 +278,13 @@ int main(argc,argv)
do do
{ {
char answer[128]; char answer[128];
printf("The file %s exist. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try); int ret;
scanf("%1s",answer); printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ; rep = answer[0] ;
if ((rep>='a') && (rep<='z')) if ((rep>='a') && (rep<='z'))
rep -= 0x20; rep -= 0x20;
...@@ -305,7 +319,12 @@ int main(argc,argv) ...@@ -305,7 +319,12 @@ int main(argc,argv)
for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++) for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
{ {
if (((*(argv[i]))!='-') && ((*(argv[i]))!='/')) if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
((argv[i][1]=='o') || (argv[i][1]=='O') ||
(argv[i][1]=='a') || (argv[i][1]=='A') ||
(argv[i][1]=='p') || (argv[i][1]=='P') ||
((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
(strlen(argv[i]) == 2)))
{ {
FILE * fin; FILE * fin;
int size_read; int size_read;
...@@ -390,7 +409,11 @@ int main(argc,argv) ...@@ -390,7 +409,11 @@ int main(argc,argv)
errclose = zipClose(zf,NULL); errclose = zipClose(zf,NULL);
if (errclose != ZIP_OK) if (errclose != ZIP_OK)
printf("error in closing %s\n",filename_try); printf("error in closing %s\n",filename_try);
} }
else
{
do_help();
}
free(buf); free(buf);
return 0; return 0;
......
/* unzip.c -- IO for uncompress .zip files using zlib /* unzip.c -- IO for uncompress .zip files using zlib
Version 1.00, September 10th, 2003 Version 1.01e, February 12th, 2005
Copyright (C) 1998-2003 Gilles Vollant Copyright (C) 1998-2005 Gilles Vollant
Read unzip.h for more info Read unzip.h for more info
*/ */
...@@ -88,7 +88,7 @@ woven in by Terry Thorsen 1/2003. ...@@ -88,7 +88,7 @@ woven in by Terry Thorsen 1/2003.
const char unz_copyright[] = const char unz_copyright[] =
" unzip 1.00 Copyright 1998-2003 Gilles Vollant - http://www.winimage.com/zLibDll"; " unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
/* unz_file_info_interntal contain internal info about a file in zipfile*/ /* unz_file_info_interntal contain internal info about a file in zipfile*/
typedef struct unz_file_info_internal_s typedef struct unz_file_info_internal_s
...@@ -798,7 +798,8 @@ extern int ZEXPORT unzGoToNextFile (file) ...@@ -798,7 +798,8 @@ extern int ZEXPORT unzGoToNextFile (file)
s=(unz_s*)file; s=(unz_s*)file;
if (!s->current_file_ok) if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE; return UNZ_END_OF_LIST_OF_FILE;
if (s->num_file+1==s->gi.number_entry) if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */
if (s->num_file+1==s->gi.number_entry)
return UNZ_END_OF_LIST_OF_FILE; return UNZ_END_OF_LIST_OF_FILE;
s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename + s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
...@@ -1136,7 +1137,10 @@ extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password) ...@@ -1136,7 +1137,10 @@ extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password)
if (err == Z_OK) if (err == Z_OK)
pfile_in_zip_read_info->stream_initialised=1; pfile_in_zip_read_info->stream_initialised=1;
else else
{
TRYFREE(pfile_in_zip_read_info);
return err; return err;
}
/* windowBits is passed < 0 to tell that there is no zlib header. /* windowBits is passed < 0 to tell that there is no zlib header.
* Note that in this case inflate *requires* an extra "dummy" byte * Note that in this case inflate *requires* an extra "dummy" byte
* after the compressed stream in order to complete decompression and * after the compressed stream in order to complete decompression and
...@@ -1244,9 +1248,17 @@ extern int ZEXPORT unzReadCurrentFile (file, buf, len) ...@@ -1244,9 +1248,17 @@ extern int ZEXPORT unzReadCurrentFile (file, buf, len)
pfile_in_zip_read_info->stream.avail_out = (uInt)len; pfile_in_zip_read_info->stream.avail_out = (uInt)len;
if (len>pfile_in_zip_read_info->rest_read_uncompressed) if ((len>pfile_in_zip_read_info->rest_read_uncompressed) &&
(!(pfile_in_zip_read_info->raw)))
pfile_in_zip_read_info->stream.avail_out =
(uInt)pfile_in_zip_read_info->rest_read_uncompressed;
if ((len>pfile_in_zip_read_info->rest_read_compressed+
pfile_in_zip_read_info->stream.avail_in) &&
(pfile_in_zip_read_info->raw))
pfile_in_zip_read_info->stream.avail_out = pfile_in_zip_read_info->stream.avail_out =
(uInt)pfile_in_zip_read_info->rest_read_uncompressed; (uInt)pfile_in_zip_read_info->rest_read_compressed+
pfile_in_zip_read_info->stream.avail_in;
while (pfile_in_zip_read_info->stream.avail_out>0) while (pfile_in_zip_read_info->stream.avail_out>0)
{ {
...@@ -1339,6 +1351,9 @@ extern int ZEXPORT unzReadCurrentFile (file, buf, len) ...@@ -1339,6 +1351,9 @@ extern int ZEXPORT unzReadCurrentFile (file, buf, len)
*/ */
err=inflate(&pfile_in_zip_read_info->stream,flush); err=inflate(&pfile_in_zip_read_info->stream,flush);
if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL))
err = Z_DATA_ERROR;
uTotalOutAfter = pfile_in_zip_read_info->stream.total_out; uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
uOutThis = uTotalOutAfter-uTotalOutBefore; uOutThis = uTotalOutAfter-uTotalOutBefore;
...@@ -1461,7 +1476,7 @@ extern int ZEXPORT unzGetLocalExtrafield (file,buf,len) ...@@ -1461,7 +1476,7 @@ extern int ZEXPORT unzGetLocalExtrafield (file,buf,len)
if (ZREAD(pfile_in_zip_read_info->z_filefunc, if (ZREAD(pfile_in_zip_read_info->z_filefunc,
pfile_in_zip_read_info->filestream, pfile_in_zip_read_info->filestream,
buf,size_to_read)!=size_to_read) buf,read_now)!=read_now)
return UNZ_ERRNO; return UNZ_ERRNO;
return (int)read_now; return (int)read_now;
...@@ -1544,3 +1559,40 @@ extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf) ...@@ -1544,3 +1559,40 @@ extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf)
*(szComment+s->gi.size_comment)='\0'; *(szComment+s->gi.size_comment)='\0';
return (int)uReadThis; return (int)uReadThis;
} }
/* Additions by RX '2004 */
extern uLong ZEXPORT unzGetOffset (file)
unzFile file;
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return 0;
if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff)
if (s->num_file==s->gi.number_entry)
return 0;
return s->pos_in_central_dir;
}
extern int ZEXPORT unzSetOffset (file, pos)
unzFile file;
uLong pos;
{
unz_s* s;
int err;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
s->pos_in_central_dir = pos;
s->num_file = s->gi.number_entry; /* hack */
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
/* unzip.h -- IO for uncompress .zip files using zlib /* unzip.h -- IO for uncompress .zip files using zlib
Version 1.00, September 10th, 2003 Version 1.01e, February 12th, 2005
Copyright (C) 1998-2003 Gilles Vollant Copyright (C) 1998-2005 Gilles Vollant
This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
WinZip, InfoZip tools and compatible. WinZip, InfoZip tools and compatible.
Encryption and multi volume ZipFile (span) are not supported.
Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported Old compressions used by old PKZip 1.x are not supported
...@@ -335,6 +337,16 @@ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, ...@@ -335,6 +337,16 @@ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
the error code the error code
*/ */
/***************************************************************************/
/* Get the current file offset */
extern uLong ZEXPORT unzGetOffset (unzFile file);
/* Set the current file offset */
extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
/* zip.c -- IO on .zip files using zlib /* zip.c -- IO on .zip files using zlib
Version 1.00, September 10th, 2003 Version 1.01e, February 12th, 2005
Copyright (C) 1998-2003 Gilles Vollant 27 Dec 2004 Rolf Kalbermatter
Modification to zipOpen2 to support globalComment retrieval.
Copyright (C) 1998-2005 Gilles Vollant
Read zip.h for more info Read zip.h for more info
*/ */
...@@ -77,7 +80,7 @@ ...@@ -77,7 +80,7 @@
#endif #endif
#endif #endif
const char zip_copyright[] = const char zip_copyright[] =
" zip 1.00 Copyright 1998-2003 Gilles Vollant - http://www.winimage.com/zLibDll"; " zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
#define SIZEDATA_INDATABLOCK (4096-(4*4)) #define SIZEDATA_INDATABLOCK (4096-(4*4))
...@@ -143,6 +146,9 @@ typedef struct ...@@ -143,6 +146,9 @@ typedef struct
uLong begin_pos; /* position of the beginning of the zipfile */ uLong begin_pos; /* position of the beginning of the zipfile */
uLong add_position_when_writting_offset; uLong add_position_when_writting_offset;
uLong number_entry; uLong number_entry;
#ifndef NO_ADDFILEINEXISTINGZIP
char *globalcomment;
#endif
} zip_internal; } zip_internal;
...@@ -265,10 +271,19 @@ local int ziplocal_putValue (pzlib_filefunc_def, filestream, x, nbByte) ...@@ -265,10 +271,19 @@ local int ziplocal_putValue (pzlib_filefunc_def, filestream, x, nbByte)
{ {
unsigned char buf[4]; unsigned char buf[4];
int n; int n;
for (n = 0; n < nbByte; n++) { for (n = 0; n < nbByte; n++)
{
buf[n] = (unsigned char)(x & 0xff); buf[n] = (unsigned char)(x & 0xff);
x >>= 8; x >>= 8;
} }
if (x != 0)
{ /* data overflow - hack for ZIP64 (X Roche) */
for (n = 0; n < nbByte; n++)
{
buf[n] = 0xff;
}
}
if (ZWRITE(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte) if (ZWRITE(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte)
return ZIP_ERRNO; return ZIP_ERRNO;
else else
...@@ -287,7 +302,16 @@ local void ziplocal_putValue_inmemory (dest, x, nbByte) ...@@ -287,7 +302,16 @@ local void ziplocal_putValue_inmemory (dest, x, nbByte)
buf[n] = (unsigned char)(x & 0xff); buf[n] = (unsigned char)(x & 0xff);
x >>= 8; x >>= 8;
} }
if (x != 0)
{ /* data overflow - hack for ZIP64 */
for (n = 0; n < nbByte; n++)
{
buf[n] = 0xff;
}
}
} }
/****************************************************************************/ /****************************************************************************/
...@@ -514,6 +538,7 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc ...@@ -514,6 +538,7 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc
/* now we add file in a zipfile */ /* now we add file in a zipfile */
# ifndef NO_ADDFILEINEXISTINGZIP # ifndef NO_ADDFILEINEXISTINGZIP
ziinit.globalcomment = NULL;
if (append == APPEND_STATUS_ADDINZIP) if (append == APPEND_STATUS_ADDINZIP)
{ {
uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/ uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
...@@ -574,7 +599,7 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc ...@@ -574,7 +599,7 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc
if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK) if (ziplocal_getLong(&ziinit.z_filefunc, ziinit.filestream,&offset_central_dir)!=ZIP_OK)
err=ZIP_ERRNO; err=ZIP_ERRNO;
/* zipfile comment length */ /* zipfile global comment length */
if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK) if (ziplocal_getShort(&ziinit.z_filefunc, ziinit.filestream,&size_comment)!=ZIP_OK)
err=ZIP_ERRNO; err=ZIP_ERRNO;
...@@ -588,9 +613,19 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc ...@@ -588,9 +613,19 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc
return NULL; return NULL;
} }
if (size_comment>0)
{
ziinit.globalcomment = ALLOC(size_comment+1);
if (ziinit.globalcomment)
{
size_comment = ZREAD(ziinit.z_filefunc, ziinit.filestream,ziinit.globalcomment,size_comment);
ziinit.globalcomment[size_comment]=0;
}
}
byte_before_the_zipfile = central_pos - byte_before_the_zipfile = central_pos -
(offset_central_dir+size_central_dir); (offset_central_dir+size_central_dir);
ziinit.add_position_when_writting_offset = byte_before_the_zipfile ; ziinit.add_position_when_writting_offset = byte_before_the_zipfile;
{ {
uLong size_central_dir_to_read = size_central_dir; uLong size_central_dir_to_read = size_central_dir;
...@@ -623,10 +658,18 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc ...@@ -623,10 +658,18 @@ extern zipFile ZEXPORT zipOpen2 (pathname, append, globalcomment, pzlib_filefunc
offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0) offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0)
err=ZIP_ERRNO; err=ZIP_ERRNO;
} }
if (globalcomment)
{
*globalcomment = ziinit.globalcomment;
}
# endif /* !NO_ADDFILEINEXISTINGZIP*/ # endif /* !NO_ADDFILEINEXISTINGZIP*/
if (err != ZIP_OK) if (err != ZIP_OK)
{ {
# ifndef NO_ADDFILEINEXISTINGZIP
TRYFREE(ziinit.globalcomment);
# endif /* !NO_ADDFILEINEXISTINGZIP*/
TRYFREE(zi); TRYFREE(zi);
return NULL; return NULL;
} }
...@@ -699,9 +742,9 @@ extern int ZEXPORT zipOpenNewFileInZip3 (file, filename, zipfi, ...@@ -699,9 +742,9 @@ extern int ZEXPORT zipOpenNewFileInZip3 (file, filename, zipfi,
if (comment==NULL) if (comment==NULL)
size_comment = 0; size_comment = 0;
else else
size_comment = strlen(comment); size_comment = (uInt)strlen(comment);
size_filename = strlen(filename); size_filename = (uInt)strlen(filename);
if (zipfi == NULL) if (zipfi == NULL)
zi->ci.dosDate = 0; zi->ci.dosDate = 0;
...@@ -1094,7 +1137,7 @@ extern int ZEXPORT zipClose (file, global_comment) ...@@ -1094,7 +1137,7 @@ extern int ZEXPORT zipClose (file, global_comment)
zip_internal* zi; zip_internal* zi;
int err = 0; int err = 0;
uLong size_centraldir = 0; uLong size_centraldir = 0;
uLong centraldir_pos_inzip ; uLong centraldir_pos_inzip;
uInt size_global_comment; uInt size_global_comment;
if (file == NULL) if (file == NULL)
return ZIP_PARAMERROR; return ZIP_PARAMERROR;
...@@ -1105,11 +1148,14 @@ extern int ZEXPORT zipClose (file, global_comment) ...@@ -1105,11 +1148,14 @@ extern int ZEXPORT zipClose (file, global_comment)
err = zipCloseFileInZip (file); err = zipCloseFileInZip (file);
} }
#ifndef NO_ADDFILEINEXISTINGZIP
if (global_comment==NULL)
global_comment = zi->globalcomment;
#endif
if (global_comment==NULL) if (global_comment==NULL)
size_global_comment = 0; size_global_comment = 0;
else else
size_global_comment = strlen(global_comment); size_global_comment = (uInt)strlen(global_comment);
centraldir_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream); centraldir_pos_inzip = ZTELL(zi->z_filefunc,zi->filestream);
if (err==ZIP_OK) if (err==ZIP_OK)
...@@ -1164,6 +1210,9 @@ extern int ZEXPORT zipClose (file, global_comment) ...@@ -1164,6 +1210,9 @@ extern int ZEXPORT zipClose (file, global_comment)
if (err == ZIP_OK) if (err == ZIP_OK)
err = ZIP_ERRNO; err = ZIP_ERRNO;
#ifndef NO_ADDFILEINEXISTINGZIP
TRYFREE(zi->globalcomment);
#endif
TRYFREE(zi); TRYFREE(zi);
return err; return err;
......
/* zip.h -- IO for compress .zip files using zlib /* zip.h -- IO for compress .zip files using zlib
Version 1.00, September 10th, 2003 Version 1.01e, February 12th, 2005
Copyright (C) 1998-2003 Gilles Vollant Copyright (C) 1998-2005 Gilles Vollant
This unzip package allow creates .ZIP file, compatible with PKZip 2.04g This unzip package allow creates .ZIP file, compatible with PKZip 2.04g
WinZip, InfoZip tools and compatible. WinZip, InfoZip tools and compatible.
Encryption and multi volume ZipFile (span) are not supported. Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported Old compressions used by old PKZip 1.x are not supported
For uncompress .zip file, look at unzip.h For uncompress .zip file, look at unzip.h
...@@ -212,7 +213,6 @@ extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); ...@@ -212,7 +213,6 @@ extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
Close the current file in the zipfile Close the current file in the zipfile
*/ */
extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
uLong uncompressed_size, uLong uncompressed_size,
uLong crc32)); uLong crc32));
......
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug.ActiveCfg = Debug|Win32
{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug.Build.0 = Debug|Win32
{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release.ActiveCfg = Release|Win32
{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding = "Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.00"
Name="testzlib"
ProjectGUID="{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;ZLIB_WINAPI;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/testzlib.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/testzlib.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="Release"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
OmitFramePointers="TRUE"
PreprocessorDefinitions="WIN32;ZLIB_WINAPI;NDEBUG;_CONSOLE"
StringPooling="TRUE"
RuntimeLibrary="4"
EnableFunctionLevelLinking="TRUE"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/testzlib.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
OptimizeForWindows98="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
</Configuration>
</Configurations>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm">
<File
RelativePath="testzlib.c">
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc">
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
</Filter>
<File
RelativePath="zlibwapi.lib">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
/* /*
* untgz.c -- Display contents and extract files from a gzip'd TAR file * untgz.c -- Display contents and extract files from a gzip'd TAR file
* *
* written by "Pedro A. Aranda Guti\irrez" <paag@tid.es> * written by Pedro A. Aranda Gutierrez <paag@tid.es>
* adaptation to Unix by Jean-loup Gailly <jloup@gzip.org> * adaptation to Unix by Jean-loup Gailly <jloup@gzip.org>
* various fixes by Cosmin Truta <cosmint@cs.ubbcluj.ro> * various fixes by Cosmin Truta <cosmint@cs.ubbcluj.ro>
*/ */
...@@ -15,10 +15,10 @@ ...@@ -15,10 +15,10 @@
#include "zlib.h" #include "zlib.h"
#ifdef unix #ifdef unix
# include <unistd.h> # include <unistd.h>
#else #else
# include <direct.h> # include <direct.h>
# include <io.h> # include <io.h>
#endif #endif
#ifdef WIN32 #ifdef WIN32
...@@ -28,8 +28,9 @@ ...@@ -28,8 +28,9 @@
# endif # endif
# define mkdir(dirname,mode) _mkdir(dirname) # define mkdir(dirname,mode) _mkdir(dirname)
# ifdef _MSC_VER # ifdef _MSC_VER
# define strdup(str) _strdup(str)
# define access(path,mode) _access(path,mode) # define access(path,mode) _access(path,mode)
# define chmod(path,mode) _chmod(path,mode)
# define strdup(str) _strdup(str)
# endif # endif
#else #else
# include <utime.h> # include <utime.h>
...@@ -48,7 +49,21 @@ ...@@ -48,7 +49,21 @@
#define FIFOTYPE '6' /* FIFO special */ #define FIFOTYPE '6' /* FIFO special */
#define CONTTYPE '7' /* reserved */ #define CONTTYPE '7' /* reserved */
#define BLOCKSIZE 512 /* GNU tar extensions */
#define GNUTYPE_DUMPDIR 'D' /* file names from dumped directory */
#define GNUTYPE_LONGLINK 'K' /* long link name */
#define GNUTYPE_LONGNAME 'L' /* long file name */
#define GNUTYPE_MULTIVOL 'M' /* continuation of file from another volume */
#define GNUTYPE_NAMES 'N' /* file name that does not fit into main hdr */
#define GNUTYPE_SPARSE 'S' /* sparse file */
#define GNUTYPE_VOLHDR 'V' /* tape/volume header */
/* tar header */
#define BLOCKSIZE 512
#define SHORTNAMESIZE 100
struct tar_header struct tar_header
{ /* byte offset */ { /* byte offset */
...@@ -71,11 +86,20 @@ struct tar_header ...@@ -71,11 +86,20 @@ struct tar_header
/* 500 */ /* 500 */
}; };
union tar_buffer { union tar_buffer
{
char buffer[BLOCKSIZE]; char buffer[BLOCKSIZE];
struct tar_header header; struct tar_header header;
}; };
struct attr_item
{
struct attr_item *next;
char *fname;
int mode;
time_t time;
};
enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID }; enum { TGZ_EXTRACT, TGZ_LIST, TGZ_INVALID };
char *TGZfname OF((const char *)); char *TGZfname OF((const char *));
...@@ -84,6 +108,9 @@ void TGZnotfound OF((const char *)); ...@@ -84,6 +108,9 @@ void TGZnotfound OF((const char *));
int getoct OF((char *, int)); int getoct OF((char *, int));
char *strtime OF((time_t *)); char *strtime OF((time_t *));
int setfiletime OF((char *, time_t)); int setfiletime OF((char *, time_t));
void push_attr OF((struct attr_item **, char *, int, time_t));
void restore_attr OF((struct attr_item **));
int ExprMatch OF((char *, char *)); int ExprMatch OF((char *, char *));
int makedir OF((char *)); int makedir OF((char *));
...@@ -221,7 +248,42 @@ int setfiletime (char *fname,time_t ftime) ...@@ -221,7 +248,42 @@ int setfiletime (char *fname,time_t ftime)
} }
/* regular expression matching */ /* push file attributes */
void push_attr(struct attr_item **list,char *fname,int mode,time_t time)
{
struct attr_item *item;
item = (struct attr_item *)malloc(sizeof(struct attr_item));
if (item == NULL)
error("Out of memory");
item->fname = strdup(fname);
item->mode = mode;
item->time = time;
item->next = *list;
*list = item;
}
/* restore file attributes */
void restore_attr(struct attr_item **list)
{
struct attr_item *item, *prev;
for (item = *list; item != NULL; )
{
setfiletime(item->fname,item->time);
chmod(item->fname,item->mode);
prev = item;
item = item->next;
free(prev);
}
*list = NULL;
}
/* match regular expression */
#define ISSPECIAL(c) (((c) == '*') || ((c) == '/')) #define ISSPECIAL(c) (((c) == '*') || ((c) == '/'))
...@@ -332,6 +394,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -332,6 +394,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
char fname[BLOCKSIZE]; char fname[BLOCKSIZE];
int tarmode; int tarmode;
time_t tartime; time_t tartime;
struct attr_item *attributes = NULL;
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" date time size file\n" printf(" date time size file\n"
...@@ -354,14 +417,15 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -354,14 +417,15 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
/* /*
* If we have to get a tar header * If we have to get a tar header
*/ */
if (getheader == 1) if (getheader >= 1)
{ {
/* /*
* if we met the end of the tar * if we met the end of the tar
* or the end-of-tar block, * or the end-of-tar block,
* we are done * we are done
*/ */
if ((len == 0) || (buffer.header.name[0] == 0)) break; if (len == 0 || buffer.header.name[0] == 0)
break;
tarmode = getoct(buffer.header.mode,8); tarmode = getoct(buffer.header.mode,8);
tartime = (time_t)getoct(buffer.header.mtime,12); tartime = (time_t)getoct(buffer.header.mtime,12);
...@@ -371,8 +435,25 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -371,8 +435,25 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
action = TGZ_INVALID; action = TGZ_INVALID;
} }
strcpy(fname,buffer.header.name); if (getheader == 1)
{
strncpy(fname,buffer.header.name,SHORTNAMESIZE);
if (fname[SHORTNAMESIZE-1] != 0)
fname[SHORTNAMESIZE] = 0;
}
else
{
/*
* The file name is longer than SHORTNAMESIZE
*/
if (strncmp(fname,buffer.header.name,SHORTNAMESIZE-1) != 0)
error("bad long name");
getheader = 1;
}
/*
* Act according to the type flag
*/
switch (buffer.header.typeflag) switch (buffer.header.typeflag)
{ {
case DIRTYPE: case DIRTYPE:
...@@ -381,7 +462,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -381,7 +462,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
if (action == TGZ_EXTRACT) if (action == TGZ_EXTRACT)
{ {
makedir(fname); makedir(fname);
setfiletime(fname,tartime); push_attr(&attributes,fname,tarmode,tartime);
} }
break; break;
case REGTYPE: case REGTYPE:
...@@ -419,6 +500,24 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -419,6 +500,24 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
} }
getheader = 0; getheader = 0;
break; break;
case GNUTYPE_LONGLINK:
case GNUTYPE_LONGNAME:
remaining = getoct(buffer.header.size,12);
if (remaining < 0 || remaining >= BLOCKSIZE)
{
action = TGZ_INVALID;
break;
}
len = gzread(in, fname, BLOCKSIZE);
if (len < 0)
error(gzerror(in, &err));
if (fname[BLOCKSIZE-1] != 0 || (int)strlen(fname) > remaining)
{
action = TGZ_INVALID;
break;
}
getheader = 2;
break;
default: default:
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" %s <---> %s\n",strtime(&tartime),fname); printf(" %s <---> %s\n",strtime(&tartime),fname);
...@@ -433,7 +532,8 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -433,7 +532,8 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
{ {
if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes)
{ {
fprintf(stderr,"%s: Error writing %s -- skipping\n",prog,fname); fprintf(stderr,
"%s: Error writing %s -- skipping\n",prog,fname);
fclose(outfile); fclose(outfile);
outfile = NULL; outfile = NULL;
remove(fname); remove(fname);
...@@ -450,7 +550,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -450,7 +550,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
fclose(outfile); fclose(outfile);
outfile = NULL; outfile = NULL;
if (action != TGZ_INVALID) if (action != TGZ_INVALID)
setfiletime(fname,tartime); push_attr(&attributes,fname,tarmode,tartime);
} }
} }
...@@ -464,6 +564,11 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -464,6 +564,11 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
} }
} }
/*
* Restore file modes and time stamps
*/
restore_attr(&attributes);
if (gzclose(in) != Z_OK) if (gzclose(in) != Z_OK)
error("failed gzclose"); error("failed gzclose");
...@@ -475,7 +580,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv) ...@@ -475,7 +580,7 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
void help(int exitval) void help(int exitval)
{ {
printf("untgz version 0.2\n" printf("untgz version 0.2.1\n"
" using zlib version %s\n\n", " using zlib version %s\n\n",
zlibVersion()); zlibVersion());
printf("Usage: untgz file.tgz extract all files\n" printf("Usage: untgz file.tgz extract all files\n"
......
See below some functions declarations for Visual Basic.
Frequently Asked Question:
Q: Each time I use the compress function I get the -5 error (not enough
room in the output buffer).
A: Make sure that the length of the compressed buffer is passed by
reference ("as any"), not by value ("as long"). Also check that
before the call of compress this length is equal to the total size of
the compressed buffer and not zero.
From: "Jon Caruana" <jon-net@usa.net>
Subject: Re: How to port zlib declares to vb?
Date: Mon, 28 Oct 1996 18:33:03 -0600
Got the answer! (I haven't had time to check this but it's what I got, and
looks correct):
He has the following routines working:
compress
uncompress
gzopen
gzwrite
gzread
gzclose
Declares follow: (Quoted from Carlos Rios <c_rios@sonda.cl>, in Vb4 form)
#If Win16 Then 'Use Win16 calls.
Declare Function compress Lib "ZLIB.DLL" (ByVal compr As
String, comprLen As Any, ByVal buf As String, ByVal buflen
As Long) As Integer
Declare Function uncompress Lib "ZLIB.DLL" (ByVal uncompr
As String, uncomprLen As Any, ByVal compr As String, ByVal
lcompr As Long) As Integer
Declare Function gzopen Lib "ZLIB.DLL" (ByVal filePath As
String, ByVal mode As String) As Long
Declare Function gzread Lib "ZLIB.DLL" (ByVal file As
Long, ByVal uncompr As String, ByVal uncomprLen As Integer)
As Integer
Declare Function gzwrite Lib "ZLIB.DLL" (ByVal file As
Long, ByVal uncompr As String, ByVal uncomprLen As Integer)
As Integer
Declare Function gzclose Lib "ZLIB.DLL" (ByVal file As
Long) As Integer
#Else
Declare Function compress Lib "ZLIB32.DLL"
(ByVal compr As String, comprLen As Any, ByVal buf As
String, ByVal buflen As Long) As Integer
Declare Function uncompress Lib "ZLIB32.DLL"
(ByVal uncompr As String, uncomprLen As Any, ByVal compr As
String, ByVal lcompr As Long) As Long
Declare Function gzopen Lib "ZLIB32.DLL"
(ByVal file As String, ByVal mode As String) As Long
Declare Function gzread Lib "ZLIB32.DLL"
(ByVal file As Long, ByVal uncompr As String, ByVal
uncomprLen As Long) As Long
Declare Function gzwrite Lib "ZLIB32.DLL"
(ByVal file As Long, ByVal uncompr As String, ByVal
uncomprLen As Long) As Long
Declare Function gzclose Lib "ZLIB32.DLL"
(ByVal file As Long) As Long
#End If
-Jon Caruana
jon-net@usa.net
Microsoft Sitebuilder Network Level 1 Member - HTML Writer's Guild Member
Here is another example from Michael <michael_borgsys@hotmail.com> that he
says conforms to the VB guidelines, and that solves the problem of not
knowing the uncompressed size by storing it at the end of the file:
'Calling the functions:
'bracket meaning: <parameter> [optional] {Range of possible values}
'Call subCompressFile(<path with filename to compress> [, <path with
filename to write to>, [level of compression {1..9}]])
'Call subUncompressFile(<path with filename to compress>)
Option Explicit
Private lngpvtPcnSml As Long 'Stores value for 'lngPercentSmaller'
Private Const SUCCESS As Long = 0
Private Const strFilExt As String = ".cpr"
Private Declare Function lngfncCpr Lib "zlib.dll" Alias "compress2" (ByRef
dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long,
ByVal level As Integer) As Long
Private Declare Function lngfncUcp Lib "zlib.dll" Alias "uncompress" (ByRef
dest As Any, ByRef destLen As Any, ByRef src As Any, ByVal srcLen As Long)
As Long
Public Sub subCompressFile(ByVal strargOriFilPth As String, Optional ByVal
strargCprFilPth As String, Optional ByVal intLvl As Integer = 9)
Dim strCprPth As String
Dim lngOriSiz As Long
Dim lngCprSiz As Long
Dim bytaryOri() As Byte
Dim bytaryCpr() As Byte
lngOriSiz = FileLen(strargOriFilPth)
ReDim bytaryOri(lngOriSiz - 1)
Open strargOriFilPth For Binary Access Read As #1
Get #1, , bytaryOri()
Close #1
strCprPth = IIf(strargCprFilPth = "", strargOriFilPth, strargCprFilPth)
'Select file path and name
strCprPth = strCprPth & IIf(Right(strCprPth, Len(strFilExt)) =
strFilExt, "", strFilExt) 'Add file extension if not exists
lngCprSiz = (lngOriSiz * 1.01) + 12 'Compression needs temporary a bit
more space then original file size
ReDim bytaryCpr(lngCprSiz - 1)
If lngfncCpr(bytaryCpr(0), lngCprSiz, bytaryOri(0), lngOriSiz, intLvl) =
SUCCESS Then
lngpvtPcnSml = (1# - (lngCprSiz / lngOriSiz)) * 100
ReDim Preserve bytaryCpr(lngCprSiz - 1)
Open strCprPth For Binary Access Write As #1
Put #1, , bytaryCpr()
Put #1, , lngOriSiz 'Add the the original size value to the end
(last 4 bytes)
Close #1
Else
MsgBox "Compression error"
End If
Erase bytaryCpr
Erase bytaryOri
End Sub
Public Sub subUncompressFile(ByVal strargFilPth As String)
Dim bytaryCpr() As Byte
Dim bytaryOri() As Byte
Dim lngOriSiz As Long
Dim lngCprSiz As Long
Dim strOriPth As String
lngCprSiz = FileLen(strargFilPth)
ReDim bytaryCpr(lngCprSiz - 1)
Open strargFilPth For Binary Access Read As #1
Get #1, , bytaryCpr()
Close #1
'Read the original file size value:
lngOriSiz = bytaryCpr(lngCprSiz - 1) * (2 ^ 24) _
+ bytaryCpr(lngCprSiz - 2) * (2 ^ 16) _
+ bytaryCpr(lngCprSiz - 3) * (2 ^ 8) _
+ bytaryCpr(lngCprSiz - 4)
ReDim Preserve bytaryCpr(lngCprSiz - 5) 'Cut of the original size value
ReDim bytaryOri(lngOriSiz - 1)
If lngfncUcp(bytaryOri(0), lngOriSiz, bytaryCpr(0), lngCprSiz) = SUCCESS
Then
strOriPth = Left(strargFilPth, Len(strargFilPth) - Len(strFilExt))
Open strOriPth For Binary Access Write As #1
Put #1, , bytaryOri()
Close #1
Else
MsgBox "Uncompression error"
End If
Erase bytaryCpr
Erase bytaryOri
End Sub
Public Property Get lngPercentSmaller() As Long
lngPercentSmaller = lngpvtPcnSml
End Property
VERSION 1.21 VERSION 1.23
HEAPSIZE 1048576,8192 HEAPSIZE 1048576,8192
......
/* crc32.c -- compute the CRC-32 of a data stream /* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
* *
* Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
* CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
* tables for updating the shift register in one step with three exclusive-ors * tables for updating the shift register in one step with three exclusive-ors
* instead of four steps with four exclusive-ors. This results about a factor * instead of four steps with four exclusive-ors. This results in about a
* of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
*/ */
/* @(#) $Id: crc32.c,v 1.1.1.2 2002/03/11 21:53:23 tromey Exp $ */ /* @(#) $Id: crc32.c,v 1.1.1.2 2002/03/11 21:53:23 tromey Exp $ */
/*
Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
protection on the static variables used to control the first-use generation
of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
first call get_crc_table() to initialize the tables before allowing more than
one thread to use crc32().
*/
#ifdef MAKECRCH #ifdef MAKECRCH
# include <stdio.h> # include <stdio.h>
# ifndef DYNAMIC_CRC_TABLE # ifndef DYNAMIC_CRC_TABLE
...@@ -56,15 +64,19 @@ ...@@ -56,15 +64,19 @@
# define TBLS 1 # define TBLS 1
#endif /* BYFOUR */ #endif /* BYFOUR */
/* Local functions for crc concatenation */
local unsigned long gf2_matrix_times OF((unsigned long *mat,
unsigned long vec));
local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
#ifdef DYNAMIC_CRC_TABLE #ifdef DYNAMIC_CRC_TABLE
local int crc_table_empty = 1; local volatile int crc_table_empty = 1;
local unsigned long FAR crc_table[TBLS][256]; local unsigned long FAR crc_table[TBLS][256];
local void make_crc_table OF((void)); local void make_crc_table OF((void));
#ifdef MAKECRCH #ifdef MAKECRCH
local void write_table OF((FILE *, const unsigned long FAR *)); local void write_table OF((FILE *, const unsigned long FAR *));
#endif /* MAKECRCH */ #endif /* MAKECRCH */
/* /*
Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
...@@ -95,38 +107,51 @@ local void make_crc_table() ...@@ -95,38 +107,51 @@ local void make_crc_table()
{ {
unsigned long c; unsigned long c;
int n, k; int n, k;
unsigned long poly; /* polynomial exclusive-or pattern */ unsigned long poly; /* polynomial exclusive-or pattern */
/* terms of polynomial defining this crc (except x^32): */ /* terms of polynomial defining this crc (except x^32): */
static volatile int first = 1; /* flag to limit concurrent making */
static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
/* make exclusive-or pattern from polynomial (0xedb88320UL) */ /* See if another task is already doing this (not thread-safe, but better
poly = 0UL; than nothing -- significantly reduces duration of vulnerability in
for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) case the advice about DYNAMIC_CRC_TABLE is ignored) */
poly |= 1UL << (31 - p[n]); if (first) {
first = 0;
/* generate a crc for every 8-bit value */
for (n = 0; n < 256; n++) { /* make exclusive-or pattern from polynomial (0xedb88320UL) */
c = (unsigned long)n; poly = 0UL;
for (k = 0; k < 8; k++) for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
c = c & 1 ? poly ^ (c >> 1) : c >> 1; poly |= 1UL << (31 - p[n]);
crc_table[0][n] = c;
} /* generate a crc for every 8-bit value */
for (n = 0; n < 256; n++) {
c = (unsigned long)n;
for (k = 0; k < 8; k++)
c = c & 1 ? poly ^ (c >> 1) : c >> 1;
crc_table[0][n] = c;
}
#ifdef BYFOUR #ifdef BYFOUR
/* generate crc for each value followed by one, two, and three zeros, and /* generate crc for each value followed by one, two, and three zeros,
then the byte reversal of those as well as the first table */ and then the byte reversal of those as well as the first table */
for (n = 0; n < 256; n++) { for (n = 0; n < 256; n++) {
c = crc_table[0][n]; c = crc_table[0][n];
crc_table[4][n] = REV(c); crc_table[4][n] = REV(c);
for (k = 1; k < 4; k++) { for (k = 1; k < 4; k++) {
c = crc_table[0][c & 0xff] ^ (c >> 8); c = crc_table[0][c & 0xff] ^ (c >> 8);
crc_table[k][n] = c; crc_table[k][n] = c;
crc_table[k + 4][n] = REV(c); crc_table[k + 4][n] = REV(c);
}
} }
}
#endif /* BYFOUR */ #endif /* BYFOUR */
crc_table_empty = 0; crc_table_empty = 0;
}
else { /* not first */
/* wait for the other guy to finish (not efficient, but rare) */
while (crc_table_empty)
;
}
#ifdef MAKECRCH #ifdef MAKECRCH
/* write out CRC tables to crc32.h */ /* write out CRC tables to crc32.h */
...@@ -180,9 +205,10 @@ local void write_table(out, table) ...@@ -180,9 +205,10 @@ local void write_table(out, table)
const unsigned long FAR * ZEXPORT get_crc_table() const unsigned long FAR * ZEXPORT get_crc_table()
{ {
#ifdef DYNAMIC_CRC_TABLE #ifdef DYNAMIC_CRC_TABLE
if (crc_table_empty) make_crc_table(); if (crc_table_empty)
make_crc_table();
#endif /* DYNAMIC_CRC_TABLE */ #endif /* DYNAMIC_CRC_TABLE */
return (const unsigned long FAR *)crc_table; return (const unsigned long FAR *)crc_table;
} }
/* ========================================================================= */ /* ========================================================================= */
...@@ -248,7 +274,7 @@ local unsigned long crc32_little(crc, buf, len) ...@@ -248,7 +274,7 @@ local unsigned long crc32_little(crc, buf, len)
len--; len--;
} }
buf4 = (const u4 FAR *)buf; buf4 = (const u4 FAR *)(const void FAR *)buf;
while (len >= 32) { while (len >= 32) {
DOLIT32; DOLIT32;
len -= 32; len -= 32;
...@@ -288,7 +314,7 @@ local unsigned long crc32_big(crc, buf, len) ...@@ -288,7 +314,7 @@ local unsigned long crc32_big(crc, buf, len)
len--; len--;
} }
buf4 = (const u4 FAR *)buf; buf4 = (const u4 FAR *)(const void FAR *)buf;
buf4--; buf4--;
while (len >= 32) { while (len >= 32) {
DOBIG32; DOBIG32;
...@@ -309,3 +335,89 @@ local unsigned long crc32_big(crc, buf, len) ...@@ -309,3 +335,89 @@ local unsigned long crc32_big(crc, buf, len)
} }
#endif /* BYFOUR */ #endif /* BYFOUR */
#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
/* ========================================================================= */
local unsigned long gf2_matrix_times(mat, vec)
unsigned long *mat;
unsigned long vec;
{
unsigned long sum;
sum = 0;
while (vec) {
if (vec & 1)
sum ^= *mat;
vec >>= 1;
mat++;
}
return sum;
}
/* ========================================================================= */
local void gf2_matrix_square(square, mat)
unsigned long *square;
unsigned long *mat;
{
int n;
for (n = 0; n < GF2_DIM; n++)
square[n] = gf2_matrix_times(mat, mat[n]);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine(crc1, crc2, len2)
uLong crc1;
uLong crc2;
z_off_t len2;
{
int n;
unsigned long row;
unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
/* degenerate case */
if (len2 == 0)
return crc1;
/* put operator for one zero bit in odd */
odd[0] = 0xedb88320L; /* CRC-32 polynomial */
row = 1;
for (n = 1; n < GF2_DIM; n++) {
odd[n] = row;
row <<= 1;
}
/* put operator for two zero bits in even */
gf2_matrix_square(even, odd);
/* put operator for four zero bits in odd */
gf2_matrix_square(odd, even);
/* apply len2 zeros to crc1 (first square will put the operator for one
zero byte, eight zero bits, in even) */
do {
/* apply zeros operator for this bit of len2 */
gf2_matrix_square(even, odd);
if (len2 & 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
/* if no more bits set, then done */
if (len2 == 0)
break;
/* another iteration of the loop with odd and even swapped */
gf2_matrix_square(odd, even);
if (len2 & 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
/* if no more bits set, then done */
} while (len2 != 0);
/* return combined crc */
crc1 ^= crc2;
return crc1;
}
/* deflate.c -- compress data using the deflation algorithm /* deflate.c -- compress data using the deflation algorithm
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -52,7 +52,7 @@ ...@@ -52,7 +52,7 @@
#include "deflate.h" #include "deflate.h"
const char deflate_copyright[] = const char deflate_copyright[] =
" deflate 1.2.1 Copyright 1995-2003 Jean-loup Gailly "; " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
/* /*
If you use the zlib library in a product, an acknowledgment is welcome If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot in the documentation of your product. If for some reason you cannot
...@@ -264,7 +264,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, ...@@ -264,7 +264,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
#endif #endif
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_RLE) { strategy < 0 || strategy > Z_FIXED) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
...@@ -274,6 +274,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, ...@@ -274,6 +274,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
s->strm = strm; s->strm = strm;
s->wrap = wrap; s->wrap = wrap;
s->gzhead = Z_NULL;
s->w_bits = windowBits; s->w_bits = windowBits;
s->w_size = 1 << s->w_bits; s->w_size = 1 << s->w_bits;
s->w_mask = s->w_size - 1; s->w_mask = s->w_size - 1;
...@@ -333,9 +334,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) ...@@ -333,9 +334,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
if (length < MIN_MATCH) return Z_OK; if (length < MIN_MATCH) return Z_OK;
if (length > MAX_DIST(s)) { if (length > MAX_DIST(s)) {
length = MAX_DIST(s); length = MAX_DIST(s);
#ifndef USE_DICT_HEAD
dictionary += dictLength - length; /* use the tail of the dictionary */ dictionary += dictLength - length; /* use the tail of the dictionary */
#endif
} }
zmemcpy(s->window, dictionary, length); zmemcpy(s->window, dictionary, length);
s->strstart = length; s->strstart = length;
...@@ -391,6 +390,17 @@ int ZEXPORT deflateReset (strm) ...@@ -391,6 +390,17 @@ int ZEXPORT deflateReset (strm)
} }
/* ========================================================================= */ /* ========================================================================= */
int ZEXPORT deflateSetHeader (strm, head)
z_streamp strm;
gz_headerp head;
{
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
if (strm->state->wrap != 2) return Z_STREAM_ERROR;
strm->state->gzhead = head;
return Z_OK;
}
/* ========================================================================= */
int ZEXPORT deflatePrime (strm, bits, value) int ZEXPORT deflatePrime (strm, bits, value)
z_streamp strm; z_streamp strm;
int bits; int bits;
...@@ -420,7 +430,7 @@ int ZEXPORT deflateParams(strm, level, strategy) ...@@ -420,7 +430,7 @@ int ZEXPORT deflateParams(strm, level, strategy)
#else #else
if (level == Z_DEFAULT_COMPRESSION) level = 6; if (level == Z_DEFAULT_COMPRESSION) level = 6;
#endif #endif
if (level < 0 || level > 9 || strategy < 0 || strategy > Z_RLE) { if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
func = configuration_table[s->level].func; func = configuration_table[s->level].func;
...@@ -440,6 +450,25 @@ int ZEXPORT deflateParams(strm, level, strategy) ...@@ -440,6 +450,25 @@ int ZEXPORT deflateParams(strm, level, strategy)
return err; return err;
} }
/* ========================================================================= */
int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
z_streamp strm;
int good_length;
int max_lazy;
int nice_length;
int max_chain;
{
deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
s = strm->state;
s->good_match = good_length;
s->max_lazy_match = max_lazy;
s->nice_match = nice_length;
s->max_chain_length = max_chain;
return Z_OK;
}
/* ========================================================================= /* =========================================================================
* For the default windowBits of 15 and memLevel of 8, this function returns * For the default windowBits of 15 and memLevel of 8, this function returns
* a close to exact, as well as small, upper bound on the compressed size. * a close to exact, as well as small, upper bound on the compressed size.
...@@ -548,20 +577,47 @@ int ZEXPORT deflate (strm, flush) ...@@ -548,20 +577,47 @@ int ZEXPORT deflate (strm, flush)
if (s->status == INIT_STATE) { if (s->status == INIT_STATE) {
#ifdef GZIP #ifdef GZIP
if (s->wrap == 2) { if (s->wrap == 2) {
strm->adler = crc32(0L, Z_NULL, 0);
put_byte(s, 31); put_byte(s, 31);
put_byte(s, 139); put_byte(s, 139);
put_byte(s, 8); put_byte(s, 8);
put_byte(s, 0); if (s->gzhead == NULL) {
put_byte(s, 0); put_byte(s, 0);
put_byte(s, 0); put_byte(s, 0);
put_byte(s, 0); put_byte(s, 0);
put_byte(s, 0); put_byte(s, 0);
put_byte(s, s->level == 9 ? 2 : put_byte(s, 0);
(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? put_byte(s, s->level == 9 ? 2 :
4 : 0)); (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
put_byte(s, 255); 4 : 0));
s->status = BUSY_STATE; put_byte(s, OS_CODE);
strm->adler = crc32(0L, Z_NULL, 0); s->status = BUSY_STATE;
}
else {
put_byte(s, (s->gzhead->text ? 1 : 0) +
(s->gzhead->hcrc ? 2 : 0) +
(s->gzhead->extra == Z_NULL ? 0 : 4) +
(s->gzhead->name == Z_NULL ? 0 : 8) +
(s->gzhead->comment == Z_NULL ? 0 : 16)
);
put_byte(s, (Byte)(s->gzhead->time & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
put_byte(s, s->level == 9 ? 2 :
(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
4 : 0));
put_byte(s, s->gzhead->os & 0xff);
if (s->gzhead->extra != NULL) {
put_byte(s, s->gzhead->extra_len & 0xff);
put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
}
if (s->gzhead->hcrc)
strm->adler = crc32(strm->adler, s->pending_buf,
s->pending);
s->gzindex = 0;
s->status = EXTRA_STATE;
}
} }
else else
#endif #endif
...@@ -592,6 +648,110 @@ int ZEXPORT deflate (strm, flush) ...@@ -592,6 +648,110 @@ int ZEXPORT deflate (strm, flush)
strm->adler = adler32(0L, Z_NULL, 0); strm->adler = adler32(0L, Z_NULL, 0);
} }
} }
#ifdef GZIP
if (s->status == EXTRA_STATE) {
if (s->gzhead->extra != NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size)
break;
}
put_byte(s, s->gzhead->extra[s->gzindex]);
s->gzindex++;
}
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (s->gzindex == s->gzhead->extra_len) {
s->gzindex = 0;
s->status = NAME_STATE;
}
}
else
s->status = NAME_STATE;
}
if (s->status == NAME_STATE) {
if (s->gzhead->name != NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
int val;
do {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size) {
val = 1;
break;
}
}
val = s->gzhead->name[s->gzindex++];
put_byte(s, val);
} while (val != 0);
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (val == 0) {
s->gzindex = 0;
s->status = COMMENT_STATE;
}
}
else
s->status = COMMENT_STATE;
}
if (s->status == COMMENT_STATE) {
if (s->gzhead->comment != NULL) {
uInt beg = s->pending; /* start of bytes to update crc */
int val;
do {
if (s->pending == s->pending_buf_size) {
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
flush_pending(strm);
beg = s->pending;
if (s->pending == s->pending_buf_size) {
val = 1;
break;
}
}
val = s->gzhead->comment[s->gzindex++];
put_byte(s, val);
} while (val != 0);
if (s->gzhead->hcrc && s->pending > beg)
strm->adler = crc32(strm->adler, s->pending_buf + beg,
s->pending - beg);
if (val == 0)
s->status = HCRC_STATE;
}
else
s->status = HCRC_STATE;
}
if (s->status == HCRC_STATE) {
if (s->gzhead->hcrc) {
if (s->pending + 2 > s->pending_buf_size)
flush_pending(strm);
if (s->pending + 2 <= s->pending_buf_size) {
put_byte(s, (Byte)(strm->adler & 0xff));
put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
strm->adler = crc32(0L, Z_NULL, 0);
s->status = BUSY_STATE;
}
}
else
s->status = BUSY_STATE;
}
#endif
/* Flush as much pending output as possible */ /* Flush as much pending output as possible */
if (s->pending != 0) { if (s->pending != 0) {
...@@ -704,7 +864,12 @@ int ZEXPORT deflateEnd (strm) ...@@ -704,7 +864,12 @@ int ZEXPORT deflateEnd (strm)
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
status = strm->state->status; status = strm->state->status;
if (status != INIT_STATE && status != BUSY_STATE && if (status != INIT_STATE &&
status != EXTRA_STATE &&
status != NAME_STATE &&
status != COMMENT_STATE &&
status != HCRC_STATE &&
status != BUSY_STATE &&
status != FINISH_STATE) { status != FINISH_STATE) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
...@@ -744,12 +909,12 @@ int ZEXPORT deflateCopy (dest, source) ...@@ -744,12 +909,12 @@ int ZEXPORT deflateCopy (dest, source)
ss = source->state; ss = source->state;
*dest = *source; zmemcpy(dest, source, sizeof(z_stream));
ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
if (ds == Z_NULL) return Z_MEM_ERROR; if (ds == Z_NULL) return Z_MEM_ERROR;
dest->state = (struct internal_state FAR *) ds; dest->state = (struct internal_state FAR *) ds;
*ds = *ss; zmemcpy(ds, ss, sizeof(deflate_state));
ds->strm = dest; ds->strm = dest;
ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
...@@ -838,9 +1003,11 @@ local void lm_init (s) ...@@ -838,9 +1003,11 @@ local void lm_init (s)
s->match_length = s->prev_length = MIN_MATCH-1; s->match_length = s->prev_length = MIN_MATCH-1;
s->match_available = 0; s->match_available = 0;
s->ins_h = 0; s->ins_h = 0;
#ifndef FASTEST
#ifdef ASMV #ifdef ASMV
match_init(); /* initialize the asm code */ match_init(); /* initialize the asm code */
#endif #endif
#endif
} }
#ifndef FASTEST #ifndef FASTEST
...@@ -909,7 +1076,12 @@ local uInt longest_match(s, cur_match) ...@@ -909,7 +1076,12 @@ local uInt longest_match(s, cur_match)
match = s->window + cur_match; match = s->window + cur_match;
/* Skip to next match if the match length cannot increase /* Skip to next match if the match length cannot increase
* or if the match length is less than 2: * or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/ */
#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
/* This code assumes sizeof(unsigned short) == 2. Do not use /* This code assumes sizeof(unsigned short) == 2. Do not use
...@@ -1131,6 +1303,7 @@ local void fill_window(s) ...@@ -1131,6 +1303,7 @@ local void fill_window(s)
later. (Using level 0 permanently is not an optimal usage of later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.) zlib, so we don't care about this pathological case.)
*/ */
/* %%% avoid this when Z_RLE */
n = s->hash_size; n = s->hash_size;
p = &s->head[n]; p = &s->head[n];
do { do {
...@@ -1309,12 +1482,12 @@ local block_state deflate_fast(s, flush) ...@@ -1309,12 +1482,12 @@ local block_state deflate_fast(s, flush)
* of the string with itself at the start of the input file). * of the string with itself at the start of the input file).
*/ */
#ifdef FASTEST #ifdef FASTEST
if ((s->strategy < Z_HUFFMAN_ONLY) || if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
(s->strategy == Z_RLE && s->strstart - hash_head == 1)) { (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
s->match_length = longest_match_fast (s, hash_head); s->match_length = longest_match_fast (s, hash_head);
} }
#else #else
if (s->strategy < Z_HUFFMAN_ONLY) { if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
s->match_length = longest_match (s, hash_head); s->match_length = longest_match (s, hash_head);
} else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
s->match_length = longest_match_fast (s, hash_head); s->match_length = longest_match_fast (s, hash_head);
...@@ -1418,7 +1591,7 @@ local block_state deflate_slow(s, flush) ...@@ -1418,7 +1591,7 @@ local block_state deflate_slow(s, flush)
* of window index 0 (in particular we have to avoid a match * of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file). * of the string with itself at the start of the input file).
*/ */
if (s->strategy < Z_HUFFMAN_ONLY) { if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
s->match_length = longest_match (s, hash_head); s->match_length = longest_match (s, hash_head);
} else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
s->match_length = longest_match_fast (s, hash_head); s->match_length = longest_match_fast (s, hash_head);
...@@ -1500,3 +1673,64 @@ local block_state deflate_slow(s, flush) ...@@ -1500,3 +1673,64 @@ local block_state deflate_slow(s, flush)
return flush == Z_FINISH ? finish_done : block_done; return flush == Z_FINISH ? finish_done : block_done;
} }
#endif /* FASTEST */ #endif /* FASTEST */
#if 0
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
local block_state deflate_rle(s, flush)
deflate_state *s;
int flush;
{
int bflush; /* set if current block must be flushed */
uInt run; /* length of run */
uInt max; /* maximum length of run */
uInt prev; /* byte at distance one to match */
Bytef *scan; /* scan for end of run */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest encodable run.
*/
if (s->lookahead < MAX_MATCH) {
fill_window(s);
if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
return need_more;
}
if (s->lookahead == 0) break; /* flush the current block */
}
/* See how many times the previous byte repeats */
run = 0;
if (s->strstart > 0) { /* if there is a previous byte, that is */
max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
scan = s->window + s->strstart - 1;
prev = *scan++;
do {
if (*scan++ != prev)
break;
} while (++run < max);
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (run >= MIN_MATCH) {
check_match(s, s->strstart, s->strstart - 1, run);
_tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
s->lookahead -= run;
s->strstart += run;
} else {
/* No match, output a literal byte */
Tracevv((stderr,"%c", s->window[s->strstart]));
_tr_tally_lit (s, s->window[s->strstart], bflush);
s->lookahead--;
s->strstart++;
}
if (bflush) FLUSH_BLOCK(s, 0);
}
FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done;
}
#endif
/* deflate.h -- internal compression state /* deflate.h -- internal compression state
* Copyright (C) 1995-2002 Jean-loup Gailly * Copyright (C) 1995-2004 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -49,6 +49,10 @@ ...@@ -49,6 +49,10 @@
/* All codes must not exceed MAX_BITS bits */ /* All codes must not exceed MAX_BITS bits */
#define INIT_STATE 42 #define INIT_STATE 42
#define EXTRA_STATE 69
#define NAME_STATE 73
#define COMMENT_STATE 91
#define HCRC_STATE 103
#define BUSY_STATE 113 #define BUSY_STATE 113
#define FINISH_STATE 666 #define FINISH_STATE 666
/* Stream status */ /* Stream status */
...@@ -93,9 +97,10 @@ typedef struct internal_state { ...@@ -93,9 +97,10 @@ typedef struct internal_state {
Bytef *pending_buf; /* output still pending */ Bytef *pending_buf; /* output still pending */
ulg pending_buf_size; /* size of pending_buf */ ulg pending_buf_size; /* size of pending_buf */
Bytef *pending_out; /* next pending byte to output to the stream */ Bytef *pending_out; /* next pending byte to output to the stream */
int pending; /* nb of bytes in the pending buffer */ uInt pending; /* nb of bytes in the pending buffer */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
Byte data_type; /* UNKNOWN, BINARY or ASCII */ gz_headerp gzhead; /* gzip header information to write */
uInt gzindex; /* where in extra, name, or comment */
Byte method; /* STORED (for zip only) or DEFLATED */ Byte method; /* STORED (for zip only) or DEFLATED */
int last_flush; /* value of flush param for previous deflate call */ int last_flush; /* value of flush param for previous deflate call */
......
/* example.c -- usage example of the zlib compression library /* example.c -- usage example of the zlib compression library
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2004 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -11,8 +11,6 @@ ...@@ -11,8 +11,6 @@
#ifdef STDC #ifdef STDC
# include <string.h> # include <string.h>
# include <stdlib.h> # include <stdlib.h>
#else
extern void exit OF((int));
#endif #endif
#if defined(VMS) || defined(RISCOS) #if defined(VMS) || defined(RISCOS)
......
/* gzio.c -- IO on .gz files /* gzio.c -- IO on .gz files
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
* *
* Compile this file with -DNO_GZCOMPRESS to avoid the compression code. * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
#include "zutil.h" #include "zutil.h"
#ifdef NO_DEFLATE /* for compatiblity with old definition */ #ifdef NO_DEFLATE /* for compatibility with old definition */
# define NO_GZCOMPRESS # define NO_GZCOMPRESS
#endif #endif
...@@ -220,7 +220,7 @@ gzFile ZEXPORT gzdopen (fd, mode) ...@@ -220,7 +220,7 @@ gzFile ZEXPORT gzdopen (fd, mode)
int fd; int fd;
const char *mode; const char *mode;
{ {
char name[20]; char name[46]; /* allow for up to 128-bit integers */
if (fd < 0) return (gzFile)Z_NULL; if (fd < 0) return (gzFile)Z_NULL;
sprintf(name, "<fd:%d>", fd); /* for debugging */ sprintf(name, "<fd:%d>", fd); /* for debugging */
...@@ -264,7 +264,7 @@ local int get_byte(s) ...@@ -264,7 +264,7 @@ local int get_byte(s)
if (s->z_eof) return EOF; if (s->z_eof) return EOF;
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
errno = 0; errno = 0;
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
if (ferror(s->file)) s->z_err = Z_ERRNO; if (ferror(s->file)) s->z_err = Z_ERRNO;
...@@ -300,7 +300,7 @@ local void check_header(s) ...@@ -300,7 +300,7 @@ local void check_header(s)
if (len < 2) { if (len < 2) {
if (len) s->inbuf[0] = s->stream.next_in[0]; if (len) s->inbuf[0] = s->stream.next_in[0];
errno = 0; errno = 0;
len = fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file); len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO; if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
s->stream.avail_in += len; s->stream.avail_in += len;
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
...@@ -415,6 +415,7 @@ int ZEXPORT gzread (file, buf, len) ...@@ -415,6 +415,7 @@ int ZEXPORT gzread (file, buf, len)
s->stream.avail_out--; s->stream.avail_out--;
s->back = EOF; s->back = EOF;
s->out++; s->out++;
start++;
if (s->last) { if (s->last) {
s->z_err = Z_STREAM_END; s->z_err = Z_STREAM_END;
return 1; return 1;
...@@ -436,8 +437,8 @@ int ZEXPORT gzread (file, buf, len) ...@@ -436,8 +437,8 @@ int ZEXPORT gzread (file, buf, len)
s->stream.avail_in -= n; s->stream.avail_in -= n;
} }
if (s->stream.avail_out > 0) { if (s->stream.avail_out > 0) {
s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out, s->stream.avail_out -=
s->file); (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
} }
len -= s->stream.avail_out; len -= s->stream.avail_out;
s->in += len; s->in += len;
...@@ -448,7 +449,7 @@ int ZEXPORT gzread (file, buf, len) ...@@ -448,7 +449,7 @@ int ZEXPORT gzread (file, buf, len)
if (s->stream.avail_in == 0 && !s->z_eof) { if (s->stream.avail_in == 0 && !s->z_eof) {
errno = 0; errno = 0;
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
if (ferror(s->file)) { if (ferror(s->file)) {
...@@ -488,6 +489,9 @@ int ZEXPORT gzread (file, buf, len) ...@@ -488,6 +489,9 @@ int ZEXPORT gzread (file, buf, len)
} }
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
if (len == s->stream.avail_out &&
(s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
return -1;
return (int)(len - s->stream.avail_out); return (int)(len - s->stream.avail_out);
} }
...@@ -899,6 +903,18 @@ int ZEXPORT gzeof (file) ...@@ -899,6 +903,18 @@ int ZEXPORT gzeof (file)
} }
/* =========================================================================== /* ===========================================================================
Returns 1 if reading and doing so transparently, otherwise zero.
*/
int ZEXPORT gzdirect (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'r') return 0;
return s->transparent;
}
/* ===========================================================================
Outputs a long in LSB order to the given file Outputs a long in LSB order to the given file
*/ */
local void putLong (file, x) local void putLong (file, x)
...@@ -937,7 +953,6 @@ local uLong getLong (s) ...@@ -937,7 +953,6 @@ local uLong getLong (s)
int ZEXPORT gzclose (file) int ZEXPORT gzclose (file)
gzFile file; gzFile file;
{ {
int err;
gz_stream *s = (gz_stream*)file; gz_stream *s = (gz_stream*)file;
if (s == NULL) return Z_STREAM_ERROR; if (s == NULL) return Z_STREAM_ERROR;
...@@ -946,8 +961,8 @@ int ZEXPORT gzclose (file) ...@@ -946,8 +961,8 @@ int ZEXPORT gzclose (file)
#ifdef NO_GZCOMPRESS #ifdef NO_GZCOMPRESS
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
#else #else
err = do_flush (file, Z_FINISH); if (do_flush (file, Z_FINISH) != Z_OK)
if (err != Z_OK) return destroy((gz_stream*)file); return destroy((gz_stream*)file);
putLong (s->file, s->crc); putLong (s->file, s->crc);
putLong (s->file, (uLong)(s->in & 0xffffffff)); putLong (s->file, (uLong)(s->in & 0xffffffff));
...@@ -956,10 +971,16 @@ int ZEXPORT gzclose (file) ...@@ -956,10 +971,16 @@ int ZEXPORT gzclose (file)
return destroy((gz_stream*)file); return destroy((gz_stream*)file);
} }
#ifdef STDC
# define zstrerror(errnum) strerror(errnum)
#else
# define zstrerror(errnum) ""
#endif
/* =========================================================================== /* ===========================================================================
Returns the error message for the last error which occured on the Returns the error message for the last error which occurred on the
given compressed file. errnum is set to zlib error number. If an given compressed file. errnum is set to zlib error number. If an
error occured in the file system and not in the compression library, error occurred in the file system and not in the compression library,
errnum is set to Z_ERRNO and the application may consult errno errnum is set to Z_ERRNO and the application may consult errno
to get the exact error code. to get the exact error code.
*/ */
......
/* infback.c -- inflate using a call-back interface /* infback.c -- inflate using a call-back interface
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -26,7 +26,7 @@ local void fixedtables OF((struct inflate_state FAR *state)); ...@@ -26,7 +26,7 @@ local void fixedtables OF((struct inflate_state FAR *state));
window and output buffer that is 2**windowBits bytes. window and output buffer that is 2**windowBits bytes.
*/ */
int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size) int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
z_stream FAR *strm; z_streamp strm;
int windowBits; int windowBits;
unsigned char FAR *window; unsigned char FAR *window;
const char *version; const char *version;
...@@ -50,7 +50,8 @@ int stream_size; ...@@ -50,7 +50,8 @@ int stream_size;
sizeof(struct inflate_state)); sizeof(struct inflate_state));
if (state == Z_NULL) return Z_MEM_ERROR; if (state == Z_NULL) return Z_MEM_ERROR;
Tracev((stderr, "inflate: allocated\n")); Tracev((stderr, "inflate: allocated\n"));
strm->state = (voidpf)state; strm->state = (struct internal_state FAR *)state;
state->dmax = 32768U;
state->wbits = windowBits; state->wbits = windowBits;
state->wsize = 1U << windowBits; state->wsize = 1U << windowBits;
state->window = window; state->window = window;
...@@ -238,7 +239,7 @@ struct inflate_state FAR *state; ...@@ -238,7 +239,7 @@ struct inflate_state FAR *state;
are not correct, i.e. strm is Z_NULL or the state was not initialized. are not correct, i.e. strm is Z_NULL or the state was not initialized.
*/ */
int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc) int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
z_stream FAR *strm; z_streamp strm;
in_func in; in_func in;
void FAR *in_desc; void FAR *in_desc;
out_func out; out_func out;
...@@ -434,6 +435,9 @@ void FAR *out_desc; ...@@ -434,6 +435,9 @@ void FAR *out_desc;
} }
} }
/* handle error breaks in while */
if (state->mode == BAD) break;
/* build code tables */ /* build code tables */
state->next = state->codes; state->next = state->codes;
state->lencode = (code const FAR *)(state->next); state->lencode = (code const FAR *)(state->next);
...@@ -608,7 +612,7 @@ void FAR *out_desc; ...@@ -608,7 +612,7 @@ void FAR *out_desc;
} }
int ZEXPORT inflateBackEnd(strm) int ZEXPORT inflateBackEnd(strm)
z_stream FAR *strm; z_streamp strm;
{ {
if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
......
/* inffast.c -- fast decoding /* inffast.c -- fast decoding
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2004 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
- none - none
No measurable difference: No measurable difference:
- Pentium III (Anderson) - Pentium III (Anderson)
- 68060 (Nikl) - M68060 (Nikl)
*/ */
#ifdef POSTINC #ifdef POSTINC
# define OFF 0 # define OFF 0
...@@ -74,6 +74,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ ...@@ -74,6 +74,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
unsigned char FAR *out; /* local strm->next_out */ unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */ unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */ unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */ unsigned whave; /* valid bytes in the window */
unsigned write; /* window write index */ unsigned write; /* window write index */
...@@ -98,6 +101,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ ...@@ -98,6 +101,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
out = strm->next_out - OFF; out = strm->next_out - OFF;
beg = out - (start - strm->avail_out); beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257); end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize; wsize = state->wsize;
whave = state->whave; whave = state->whave;
write = state->write; write = state->write;
...@@ -167,6 +173,13 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ ...@@ -167,6 +173,13 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */
} }
} }
dist += (unsigned)hold & ((1U << op) - 1); dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op; hold >>= op;
bits -= op; bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist)); Tracevv((stderr, "inflate: distance %u\n", dist));
......
/* inflate.c -- zlib decompression /* inflate.c -- zlib decompression
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -109,11 +109,15 @@ z_streamp strm; ...@@ -109,11 +109,15 @@ z_streamp strm;
state = (struct inflate_state FAR *)strm->state; state = (struct inflate_state FAR *)strm->state;
strm->total_in = strm->total_out = state->total = 0; strm->total_in = strm->total_out = state->total = 0;
strm->msg = Z_NULL; strm->msg = Z_NULL;
strm->adler = 1; /* to support ill-conceived Java test suite */
state->mode = HEAD; state->mode = HEAD;
state->last = 0; state->last = 0;
state->havedict = 0; state->havedict = 0;
state->dmax = 32768U;
state->head = Z_NULL;
state->wsize = 0; state->wsize = 0;
state->whave = 0; state->whave = 0;
state->write = 0;
state->hold = 0; state->hold = 0;
state->bits = 0; state->bits = 0;
state->lencode = state->distcode = state->next = state->codes; state->lencode = state->distcode = state->next = state->codes;
...@@ -121,6 +125,22 @@ z_streamp strm; ...@@ -121,6 +125,22 @@ z_streamp strm;
return Z_OK; return Z_OK;
} }
int ZEXPORT inflatePrime(strm, bits, value)
z_streamp strm;
int bits;
int value;
{
struct inflate_state FAR *state;
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state;
if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
value &= (1L << bits) - 1;
state->hold += value << state->bits;
state->bits += bits;
return Z_OK;
}
int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
z_streamp strm; z_streamp strm;
int windowBits; int windowBits;
...@@ -143,7 +163,7 @@ int stream_size; ...@@ -143,7 +163,7 @@ int stream_size;
ZALLOC(strm, 1, sizeof(struct inflate_state)); ZALLOC(strm, 1, sizeof(struct inflate_state));
if (state == Z_NULL) return Z_MEM_ERROR; if (state == Z_NULL) return Z_MEM_ERROR;
Tracev((stderr, "inflate: allocated\n")); Tracev((stderr, "inflate: allocated\n"));
strm->state = (voidpf)state; strm->state = (struct internal_state FAR *)state;
if (windowBits < 0) { if (windowBits < 0) {
state->wrap = 0; state->wrap = 0;
windowBits = -windowBits; windowBits = -windowBits;
...@@ -581,6 +601,8 @@ int flush; ...@@ -581,6 +601,8 @@ int flush;
break; break;
} }
state->flags = 0; /* expect zlib header */ state->flags = 0; /* expect zlib header */
if (state->head != Z_NULL)
state->head->done = -1;
if (!(state->wrap & 1) || /* check if zlib header allowed */ if (!(state->wrap & 1) || /* check if zlib header allowed */
#else #else
if ( if (
...@@ -596,11 +618,13 @@ int flush; ...@@ -596,11 +618,13 @@ int flush;
break; break;
} }
DROPBITS(4); DROPBITS(4);
if (BITS(4) + 8 > state->wbits) { len = BITS(4) + 8;
if (len > state->wbits) {
strm->msg = (char *)"invalid window size"; strm->msg = (char *)"invalid window size";
state->mode = BAD; state->mode = BAD;
break; break;
} }
state->dmax = 1U << len;
Tracev((stderr, "inflate: zlib header ok\n")); Tracev((stderr, "inflate: zlib header ok\n"));
strm->adler = state->check = adler32(0L, Z_NULL, 0); strm->adler = state->check = adler32(0L, Z_NULL, 0);
state->mode = hold & 0x200 ? DICTID : TYPE; state->mode = hold & 0x200 ? DICTID : TYPE;
...@@ -620,16 +644,24 @@ int flush; ...@@ -620,16 +644,24 @@ int flush;
state->mode = BAD; state->mode = BAD;
break; break;
} }
if (state->head != Z_NULL)
state->head->text = (int)((hold >> 8) & 1);
if (state->flags & 0x0200) CRC2(state->check, hold); if (state->flags & 0x0200) CRC2(state->check, hold);
INITBITS(); INITBITS();
state->mode = TIME; state->mode = TIME;
case TIME: case TIME:
NEEDBITS(32); NEEDBITS(32);
if (state->head != Z_NULL)
state->head->time = hold;
if (state->flags & 0x0200) CRC4(state->check, hold); if (state->flags & 0x0200) CRC4(state->check, hold);
INITBITS(); INITBITS();
state->mode = OS; state->mode = OS;
case OS: case OS:
NEEDBITS(16); NEEDBITS(16);
if (state->head != Z_NULL) {
state->head->xflags = (int)(hold & 0xff);
state->head->os = (int)(hold >> 8);
}
if (state->flags & 0x0200) CRC2(state->check, hold); if (state->flags & 0x0200) CRC2(state->check, hold);
INITBITS(); INITBITS();
state->mode = EXLEN; state->mode = EXLEN;
...@@ -637,15 +669,26 @@ int flush; ...@@ -637,15 +669,26 @@ int flush;
if (state->flags & 0x0400) { if (state->flags & 0x0400) {
NEEDBITS(16); NEEDBITS(16);
state->length = (unsigned)(hold); state->length = (unsigned)(hold);
if (state->head != Z_NULL)
state->head->extra_len = (unsigned)hold;
if (state->flags & 0x0200) CRC2(state->check, hold); if (state->flags & 0x0200) CRC2(state->check, hold);
INITBITS(); INITBITS();
} }
else if (state->head != Z_NULL)
state->head->extra = Z_NULL;
state->mode = EXTRA; state->mode = EXTRA;
case EXTRA: case EXTRA:
if (state->flags & 0x0400) { if (state->flags & 0x0400) {
copy = state->length; copy = state->length;
if (copy > have) copy = have; if (copy > have) copy = have;
if (copy) { if (copy) {
if (state->head != Z_NULL &&
state->head->extra != Z_NULL) {
len = state->head->extra_len - state->length;
zmemcpy(state->head->extra + len, next,
len + copy > state->head->extra_max ?
state->head->extra_max - len : copy);
}
if (state->flags & 0x0200) if (state->flags & 0x0200)
state->check = crc32(state->check, next, copy); state->check = crc32(state->check, next, copy);
have -= copy; have -= copy;
...@@ -654,6 +697,7 @@ int flush; ...@@ -654,6 +697,7 @@ int flush;
} }
if (state->length) goto inf_leave; if (state->length) goto inf_leave;
} }
state->length = 0;
state->mode = NAME; state->mode = NAME;
case NAME: case NAME:
if (state->flags & 0x0800) { if (state->flags & 0x0800) {
...@@ -661,13 +705,20 @@ int flush; ...@@ -661,13 +705,20 @@ int flush;
copy = 0; copy = 0;
do { do {
len = (unsigned)(next[copy++]); len = (unsigned)(next[copy++]);
if (state->head != Z_NULL &&
state->head->name != Z_NULL &&
state->length < state->head->name_max)
state->head->name[state->length++] = len;
} while (len && copy < have); } while (len && copy < have);
if (state->flags & 0x02000) if (state->flags & 0x0200)
state->check = crc32(state->check, next, copy); state->check = crc32(state->check, next, copy);
have -= copy; have -= copy;
next += copy; next += copy;
if (len) goto inf_leave; if (len) goto inf_leave;
} }
else if (state->head != Z_NULL)
state->head->name = Z_NULL;
state->length = 0;
state->mode = COMMENT; state->mode = COMMENT;
case COMMENT: case COMMENT:
if (state->flags & 0x1000) { if (state->flags & 0x1000) {
...@@ -675,13 +726,19 @@ int flush; ...@@ -675,13 +726,19 @@ int flush;
copy = 0; copy = 0;
do { do {
len = (unsigned)(next[copy++]); len = (unsigned)(next[copy++]);
if (state->head != Z_NULL &&
state->head->comment != Z_NULL &&
state->length < state->head->comm_max)
state->head->comment[state->length++] = len;
} while (len && copy < have); } while (len && copy < have);
if (state->flags & 0x02000) if (state->flags & 0x0200)
state->check = crc32(state->check, next, copy); state->check = crc32(state->check, next, copy);
have -= copy; have -= copy;
next += copy; next += copy;
if (len) goto inf_leave; if (len) goto inf_leave;
} }
else if (state->head != Z_NULL)
state->head->comment = Z_NULL;
state->mode = HCRC; state->mode = HCRC;
case HCRC: case HCRC:
if (state->flags & 0x0200) { if (state->flags & 0x0200) {
...@@ -693,6 +750,10 @@ int flush; ...@@ -693,6 +750,10 @@ int flush;
} }
INITBITS(); INITBITS();
} }
if (state->head != Z_NULL) {
state->head->hcrc = (int)((state->flags >> 9) & 1);
state->head->done = 1;
}
strm->adler = state->check = crc32(0L, Z_NULL, 0); strm->adler = state->check = crc32(0L, Z_NULL, 0);
state->mode = TYPE; state->mode = TYPE;
break; break;
...@@ -861,6 +922,9 @@ int flush; ...@@ -861,6 +922,9 @@ int flush;
} }
} }
/* handle error breaks in while */
if (state->mode == BAD) break;
/* build code tables */ /* build code tables */
state->next = state->codes; state->next = state->codes;
state->lencode = (code const FAR *)(state->next); state->lencode = (code const FAR *)(state->next);
...@@ -965,6 +1029,13 @@ int flush; ...@@ -965,6 +1029,13 @@ int flush;
state->offset += BITS(state->extra); state->offset += BITS(state->extra);
DROPBITS(state->extra); DROPBITS(state->extra);
} }
#ifdef INFLATE_STRICT
if (state->offset > state->dmax) {
strm->msg = (char *)"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
if (state->offset > state->whave + out - left) { if (state->offset > state->whave + out - left) {
strm->msg = (char *)"invalid distance too far back"; strm->msg = (char *)"invalid distance too far back";
state->mode = BAD; state->mode = BAD;
...@@ -1106,12 +1177,16 @@ uInt dictLength; ...@@ -1106,12 +1177,16 @@ uInt dictLength;
/* check state */ /* check state */
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state; state = (struct inflate_state FAR *)strm->state;
if (state->mode != DICT) return Z_STREAM_ERROR; if (state->wrap != 0 && state->mode != DICT)
return Z_STREAM_ERROR;
/* check for correct dictionary id */ /* check for correct dictionary id */
id = adler32(0L, Z_NULL, 0); if (state->mode == DICT) {
id = adler32(id, dictionary, dictLength); id = adler32(0L, Z_NULL, 0);
if (id != state->check) return Z_DATA_ERROR; id = adler32(id, dictionary, dictLength);
if (id != state->check)
return Z_DATA_ERROR;
}
/* copy dictionary to window */ /* copy dictionary to window */
if (updatewindow(strm, strm->avail_out)) { if (updatewindow(strm, strm->avail_out)) {
...@@ -1133,6 +1208,23 @@ uInt dictLength; ...@@ -1133,6 +1208,23 @@ uInt dictLength;
return Z_OK; return Z_OK;
} }
int ZEXPORT inflateGetHeader(strm, head)
z_streamp strm;
gz_headerp head;
{
struct inflate_state FAR *state;
/* check state */
if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state;
if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
/* save header structure */
state->head = head;
head->done = 0;
return Z_OK;
}
/* /*
Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
or when out of input. When called, *have is the number of pattern bytes or when out of input. When called, *have is the number of pattern bytes
...@@ -1235,6 +1327,7 @@ z_streamp source; ...@@ -1235,6 +1327,7 @@ z_streamp source;
struct inflate_state FAR *state; struct inflate_state FAR *state;
struct inflate_state FAR *copy; struct inflate_state FAR *copy;
unsigned char FAR *window; unsigned char FAR *window;
unsigned wsize;
/* check input */ /* check input */
if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
...@@ -1257,14 +1350,19 @@ z_streamp source; ...@@ -1257,14 +1350,19 @@ z_streamp source;
} }
/* copy state */ /* copy state */
*dest = *source; zmemcpy(dest, source, sizeof(z_stream));
*copy = *state; zmemcpy(copy, state, sizeof(struct inflate_state));
copy->lencode = copy->codes + (state->lencode - state->codes); if (state->lencode >= state->codes &&
copy->distcode = copy->codes + (state->distcode - state->codes); state->lencode <= state->codes + ENOUGH - 1) {
copy->lencode = copy->codes + (state->lencode - state->codes);
copy->distcode = copy->codes + (state->distcode - state->codes);
}
copy->next = copy->codes + (state->next - state->codes); copy->next = copy->codes + (state->next - state->codes);
if (window != Z_NULL) if (window != Z_NULL) {
zmemcpy(window, state->window, 1U << state->wbits); wsize = 1U << state->wbits;
zmemcpy(window, state->window, wsize);
}
copy->window = window; copy->window = window;
dest->state = (voidpf)copy; dest->state = (struct internal_state FAR *)copy;
return Z_OK; return Z_OK;
} }
/* inflate.h -- internal inflate state definition /* inflate.h -- internal inflate state definition
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2004 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
/* Possible inflate modes between inflate() calls */ /* Possible inflate modes between inflate() calls */
typedef enum { typedef enum {
HEAD, /* i: waiting for magic header */ HEAD, /* i: waiting for magic header */
#ifdef GUNZIP
FLAGS, /* i: waiting for method and flags (gzip) */ FLAGS, /* i: waiting for method and flags (gzip) */
TIME, /* i: waiting for modification time (gzip) */ TIME, /* i: waiting for modification time (gzip) */
OS, /* i: waiting for extra flags and operating system (gzip) */ OS, /* i: waiting for extra flags and operating system (gzip) */
...@@ -28,7 +27,6 @@ typedef enum { ...@@ -28,7 +27,6 @@ typedef enum {
NAME, /* i: waiting for end of file name (gzip) */ NAME, /* i: waiting for end of file name (gzip) */
COMMENT, /* i: waiting for end of comment (gzip) */ COMMENT, /* i: waiting for end of comment (gzip) */
HCRC, /* i: waiting for header crc (gzip) */ HCRC, /* i: waiting for header crc (gzip) */
#endif
DICTID, /* i: waiting for dictionary check value */ DICTID, /* i: waiting for dictionary check value */
DICT, /* waiting for inflateSetDictionary() call */ DICT, /* waiting for inflateSetDictionary() call */
TYPE, /* i: waiting for type bits, including last-flag bit */ TYPE, /* i: waiting for type bits, including last-flag bit */
...@@ -45,9 +43,7 @@ typedef enum { ...@@ -45,9 +43,7 @@ typedef enum {
MATCH, /* o: waiting for output space to copy string */ MATCH, /* o: waiting for output space to copy string */
LIT, /* o: waiting for output space to write literal */ LIT, /* o: waiting for output space to write literal */
CHECK, /* i: waiting for 32-bit check value */ CHECK, /* i: waiting for 32-bit check value */
#ifdef GUNZIP
LENGTH, /* i: waiting for 32-bit length (gzip) */ LENGTH, /* i: waiting for 32-bit length (gzip) */
#endif
DONE, /* finished check, done -- remain here until reset */ DONE, /* finished check, done -- remain here until reset */
BAD, /* got a data error -- remain here until reset */ BAD, /* got a data error -- remain here until reset */
MEM, /* got an inflate() memory error -- remain here until reset */ MEM, /* got an inflate() memory error -- remain here until reset */
...@@ -84,8 +80,10 @@ struct inflate_state { ...@@ -84,8 +80,10 @@ struct inflate_state {
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
int havedict; /* true if dictionary provided */ int havedict; /* true if dictionary provided */
int flags; /* gzip header method and flags (0 if zlib) */ int flags; /* gzip header method and flags (0 if zlib) */
unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
unsigned long check; /* protected copy of check value */ unsigned long check; /* protected copy of check value */
unsigned long total; /* protected copy of output count */ unsigned long total; /* protected copy of output count */
gz_headerp head; /* where to save gzip header information */
/* sliding window */ /* sliding window */
unsigned wbits; /* log base 2 of requested window size */ unsigned wbits; /* log base 2 of requested window size */
unsigned wsize; /* window size or zero if not using window */ unsigned wsize; /* window size or zero if not using window */
......
/* inftrees.c -- generate Huffman trees for efficient decoding /* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
#define MAXBITS 15 #define MAXBITS 15
const char inflate_copyright[] = const char inflate_copyright[] =
" inflate 1.2.1 Copyright 1995-2003 Mark Adler "; " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
/* /*
If you use the zlib library in a product, an acknowledgment is welcome If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot in the documentation of your product. If for some reason you cannot
...@@ -62,7 +62,7 @@ unsigned short FAR *work; ...@@ -62,7 +62,7 @@ unsigned short FAR *work;
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const unsigned short lext[31] = { /* Length codes 257..285 extra */ static const unsigned short lext[31] = { /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 76, 66}; 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
...@@ -114,7 +114,15 @@ unsigned short FAR *work; ...@@ -114,7 +114,15 @@ unsigned short FAR *work;
for (max = MAXBITS; max >= 1; max--) for (max = MAXBITS; max >= 1; max--)
if (count[max] != 0) break; if (count[max] != 0) break;
if (root > max) root = max; if (root > max) root = max;
if (max == 0) return -1; /* no codes! */ if (max == 0) { /* no symbols to code at all */
this.op = (unsigned char)64; /* invalid code marker */
this.bits = (unsigned char)1;
this.val = (unsigned short)0;
*(*table)++ = this; /* make a table to force an error */
*(*table)++ = this;
*bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min <= MAXBITS; min++) for (min = 1; min <= MAXBITS; min++)
if (count[min] != 0) break; if (count[min] != 0) break;
if (root < min) root = min; if (root < min) root = min;
...@@ -126,7 +134,7 @@ unsigned short FAR *work; ...@@ -126,7 +134,7 @@ unsigned short FAR *work;
left -= count[len]; left -= count[len];
if (left < 0) return -1; /* over-subscribed */ if (left < 0) return -1; /* over-subscribed */
} }
if (left > 0 && (type == CODES || (codes - count[0] != 1))) if (left > 0 && (type == CODES || max != 1))
return -1; /* incomplete set */ return -1; /* incomplete set */
/* generate offsets into symbol table for each length for sorting */ /* generate offsets into symbol table for each length for sorting */
...@@ -224,6 +232,7 @@ unsigned short FAR *work; ...@@ -224,6 +232,7 @@ unsigned short FAR *work;
/* replicate for those indices with low len bits equal to huff */ /* replicate for those indices with low len bits equal to huff */
incr = 1U << (len - drop); incr = 1U << (len - drop);
fill = 1U << curr; fill = 1U << curr;
min = fill; /* save offset to next table */
do { do {
fill -= incr; fill -= incr;
next[(huff >> drop) + fill] = this; next[(huff >> drop) + fill] = this;
...@@ -254,7 +263,7 @@ unsigned short FAR *work; ...@@ -254,7 +263,7 @@ unsigned short FAR *work;
drop = root; drop = root;
/* increment past last table */ /* increment past last table */
next += 1U << curr; next += min; /* here min is 1 << curr */
/* determine length of next table */ /* determine length of next table */
curr = len - drop; curr = len - drop;
...@@ -295,7 +304,6 @@ unsigned short FAR *work; ...@@ -295,7 +304,6 @@ unsigned short FAR *work;
drop = 0; drop = 0;
len = root; len = root;
next = *table; next = *table;
curr = root;
this.bits = (unsigned char)len; this.bits = (unsigned char)len;
} }
......
/* inftrees.h -- header to use inftrees.c /* inftrees.h -- header to use inftrees.c
* Copyright (C) 1995-2003 Mark Adler * Copyright (C) 1995-2005 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -36,12 +36,12 @@ typedef struct { ...@@ -36,12 +36,12 @@ typedef struct {
*/ */
/* Maximum size of dynamic tree. The maximum found in a long but non- /* Maximum size of dynamic tree. The maximum found in a long but non-
exhaustive search was 1004 code structures (850 for length/literals exhaustive search was 1444 code structures (852 for length/literals
and 154 for distances, the latter actually the result of an and 592 for distances, the latter actually the result of an
exhaustive search). The true maximum is not known, but the value exhaustive search). The true maximum is not known, but the value
below is more than safe. */ below is more than safe. */
#define ENOUGH 1440 #define ENOUGH 2048
#define MAXD 154 #define MAXD 592
/* Type of code to build for inftable() */ /* Type of code to build for inftable() */
typedef enum { typedef enum {
......
/* minigzip.c -- simulate gzip using the zlib compression library /* minigzip.c -- simulate gzip using the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -21,8 +21,6 @@ ...@@ -21,8 +21,6 @@
#ifdef STDC #ifdef STDC
# include <string.h> # include <string.h>
# include <stdlib.h> # include <stdlib.h>
#else
extern void exit OF((int));
#endif #endif
#ifdef USE_MMAP #ifdef USE_MMAP
...@@ -297,6 +295,8 @@ int main(argc, argv) ...@@ -297,6 +295,8 @@ int main(argc, argv)
break; break;
argc--, argv++; argc--, argv++;
} }
if (outmode[3] == ' ')
outmode[3] = 0;
if (argc == 0) { if (argc == 0) {
SET_BINARY_MODE(stdin); SET_BINARY_MODE(stdin);
SET_BINARY_MODE(stdout); SET_BINARY_MODE(stdout);
......
$! make libz under VMS
$! written by Martin P.J. Zinser <m.zinser@gsi.de>
$!
$! Look for the compiler used
$!
$ ccopt = ""
$ if f$getsyi("HW_MODEL").ge.1024
$ then
$ ccopt = "/prefix=all"+ccopt
$ comp = "__decc__=1"
$ if f$trnlnm("SYS").eqs."" then define sys sys$library:
$ else
$ if f$search("SYS$SYSTEM:DECC$COMPILER.EXE").eqs.""
$ then
$ comp = "__vaxc__=1"
$ if f$trnlnm("SYS").eqs."" then define sys sys$library:
$ else
$ if f$trnlnm("SYS").eqs."" then define sys decc$library_include:
$ ccopt = "/decc/prefix=all"+ccopt
$ comp = "__decc__=1"
$ endif
$ endif
$!
$! Build the thing plain or with mms
$!
$ write sys$output "Compiling Zlib sources ..."
$ if f$search("SYS$SYSTEM:MMS.EXE").eqs.""
$ then
$ dele example.obj;*,minigzip.obj;*
$ CALL MAKE adler32.OBJ "CC ''CCOPT' adler32" -
adler32.c zlib.h zconf.h
$ CALL MAKE compress.OBJ "CC ''CCOPT' compress" -
compress.c zlib.h zconf.h
$ CALL MAKE crc32.OBJ "CC ''CCOPT' crc32" -
crc32.c zlib.h zconf.h
$ CALL MAKE deflate.OBJ "CC ''CCOPT' deflate" -
deflate.c deflate.h zutil.h zlib.h zconf.h
$ CALL MAKE gzio.OBJ "CC ''CCOPT' gzio" -
gzio.c zutil.h zlib.h zconf.h
$ CALL MAKE infblock.OBJ "CC ''CCOPT' infblock" -
infblock.c zutil.h zlib.h zconf.h infblock.h
$ CALL MAKE infcodes.OBJ "CC ''CCOPT' infcodes" -
infcodes.c zutil.h zlib.h zconf.h inftrees.h
$ CALL MAKE inffast.OBJ "CC ''CCOPT' inffast" -
inffast.c zutil.h zlib.h zconf.h inffast.h
$ CALL MAKE inflate.OBJ "CC ''CCOPT' inflate" -
inflate.c zutil.h zlib.h zconf.h infblock.h
$ CALL MAKE inftrees.OBJ "CC ''CCOPT' inftrees" -
inftrees.c zutil.h zlib.h zconf.h inftrees.h
$ CALL MAKE infutil.OBJ "CC ''CCOPT' infutil" -
infutil.c zutil.h zlib.h zconf.h inftrees.h infutil.h
$ CALL MAKE trees.OBJ "CC ''CCOPT' trees" -
trees.c deflate.h zutil.h zlib.h zconf.h
$ CALL MAKE uncompr.OBJ "CC ''CCOPT' uncompr" -
uncompr.c zlib.h zconf.h
$ CALL MAKE zutil.OBJ "CC ''CCOPT' zutil" -
zutil.c zutil.h zlib.h zconf.h
$ write sys$output "Building Zlib ..."
$ CALL MAKE libz.OLB "lib/crea libz.olb *.obj" *.OBJ
$ write sys$output "Building example..."
$ CALL MAKE example.OBJ "CC ''CCOPT' example" -
example.c zlib.h zconf.h
$ call make example.exe "LINK example,libz.olb/lib" example.obj libz.olb
$ write sys$output "Building minigzip..."
$ CALL MAKE minigzip.OBJ "CC ''CCOPT' minigzip" -
minigzip.c zlib.h zconf.h
$ call make minigzip.exe -
"LINK minigzip,libz.olb/lib,x11vms:xvmsutils.olb/lib" -
minigzip.obj libz.olb
$ else
$ mms/macro=('comp')
$ endif
$ write sys$output "Zlib build completed"
$ exit
$!
$!
$MAKE: SUBROUTINE !SUBROUTINE TO CHECK DEPENDENCIES
$ V = 'F$Verify(0)
$! P1 = What we are trying to make
$! P2 = Command to make it
$! P3 - P8 What it depends on
$
$ If F$Search(P1) .Eqs. "" Then Goto Makeit
$ Time = F$CvTime(F$File(P1,"RDT"))
$arg=3
$Loop:
$ Argument = P'arg
$ If Argument .Eqs. "" Then Goto Exit
$ El=0
$Loop2:
$ File = F$Element(El," ",Argument)
$ If File .Eqs. " " Then Goto Endl
$ AFile = ""
$Loop3:
$ OFile = AFile
$ AFile = F$Search(File)
$ If AFile .Eqs. "" .Or. AFile .Eqs. OFile Then Goto NextEl
$ If F$CvTime(F$File(AFile,"RDT")) .Ges. Time Then Goto Makeit
$ Goto Loop3
$NextEL:
$ El = El + 1
$ Goto Loop2
$EndL:
$ arg=arg+1
$ If arg .Le. 8 Then Goto Loop
$ Goto Exit
$
$Makeit:
$ VV=F$VERIFY(0)
$ write sys$output P2
$ 'P2
$ VV='F$Verify(VV)
$Exit:
$ If V Then Set Verify
$ENDSUBROUTINE
/* trees.c -- output deflated data using Huffman coding /* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2003 Jean-loup Gailly * Copyright (C) 1995-2005 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -555,7 +555,7 @@ local void gen_bitlen(s, desc) ...@@ -555,7 +555,7 @@ local void gen_bitlen(s, desc)
while (n != 0) { while (n != 0) {
m = s->heap[--h]; m = s->heap[--h];
if (m > max_code) continue; if (m > max_code) continue;
if (tree[m].Len != (unsigned) bits) { if ((unsigned) tree[m].Len != (unsigned) bits) {
Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s->opt_len += ((long)bits - (long)tree[m].Len) s->opt_len += ((long)bits - (long)tree[m].Len)
*(long)tree[m].Freq; *(long)tree[m].Freq;
...@@ -930,8 +930,9 @@ void _tr_flush_block(s, buf, stored_len, eof) ...@@ -930,8 +930,9 @@ void _tr_flush_block(s, buf, stored_len, eof)
/* Build the Huffman trees unless a stored block is forced */ /* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) { if (s->level > 0) {
/* Check if the file is ascii or binary */ /* Check if the file is binary or text */
if (s->data_type == Z_UNKNOWN) set_data_type(s); if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
set_data_type(s);
/* Construct the literal and distance trees */ /* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc))); build_tree(s, (tree_desc *)(&(s->l_desc)));
...@@ -982,7 +983,7 @@ void _tr_flush_block(s, buf, stored_len, eof) ...@@ -982,7 +983,7 @@ void _tr_flush_block(s, buf, stored_len, eof)
#ifdef FORCE_STATIC #ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */ } else if (static_lenb >= 0) { /* force static trees */
#else #else
} else if (static_lenb == opt_lenb) { } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
#endif #endif
send_bits(s, (STATIC_TREES<<1)+eof, 3); send_bits(s, (STATIC_TREES<<1)+eof, 3);
compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
...@@ -1117,21 +1118,24 @@ local void compress_block(s, ltree, dtree) ...@@ -1117,21 +1118,24 @@ local void compress_block(s, ltree, dtree)
} }
/* =========================================================================== /* ===========================================================================
* Set the data type to ASCII or BINARY, using a crude approximation: * Set the data type to BINARY or TEXT, using a crude approximation:
* binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
* IN assertion: the fields freq of dyn_ltree are set and the total of all * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
* frequencies does not exceed 64K (to fit in an int on 16 bit machines). * IN assertion: the fields Freq of dyn_ltree are set.
*/ */
local void set_data_type(s) local void set_data_type(s)
deflate_state *s; deflate_state *s;
{ {
int n = 0; int n;
unsigned ascii_freq = 0;
unsigned bin_freq = 0; for (n = 0; n < 9; n++)
while (n < 7) bin_freq += s->dyn_ltree[n++].Freq; if (s->dyn_ltree[n].Freq != 0)
while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq; break;
while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq; if (n == 9)
s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII); for (n = 14; n < 32; n++)
if (s->dyn_ltree[n].Freq != 0)
break;
s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
} }
/* =========================================================================== /* ===========================================================================
......
/* zconf.h -- configuration of the zlib compression library /* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -13,43 +13,50 @@ ...@@ -13,43 +13,50 @@
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
*/ */
#ifdef Z_PREFIX #ifdef Z_PREFIX
# define deflateInit_ z_deflateInit_ # define deflateInit_ z_deflateInit_
# define deflate z_deflate # define deflate z_deflate
# define deflateEnd z_deflateEnd # define deflateEnd z_deflateEnd
# define inflateInit_ z_inflateInit_ # define inflateInit_ z_inflateInit_
# define inflate z_inflate # define inflate z_inflate
# define inflateEnd z_inflateEnd # define inflateEnd z_inflateEnd
# define deflateInit2_ z_deflateInit2_ # define deflateInit2_ z_deflateInit2_
# define deflateSetDictionary z_deflateSetDictionary # define deflateSetDictionary z_deflateSetDictionary
# define deflateCopy z_deflateCopy # define deflateCopy z_deflateCopy
# define deflateReset z_deflateReset # define deflateReset z_deflateReset
# define deflatePrime z_deflatePrime # define deflateParams z_deflateParams
# define deflateParams z_deflateParams # define deflateBound z_deflateBound
# define deflateBound z_deflateBound # define deflatePrime z_deflatePrime
# define inflateInit2_ z_inflateInit2_ # define inflateInit2_ z_inflateInit2_
# define inflateSetDictionary z_inflateSetDictionary # define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync # define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint # define inflateSyncPoint z_inflateSyncPoint
# define inflateCopy z_inflateCopy # define inflateCopy z_inflateCopy
# define inflateReset z_inflateReset # define inflateReset z_inflateReset
# define compress z_compress # define inflateBack z_inflateBack
# define compress2 z_compress2 # define inflateBackEnd z_inflateBackEnd
# define compressBound z_compressBound # define compress z_compress
# define uncompress z_uncompress # define compress2 z_compress2
# define adler32 z_adler32 # define compressBound z_compressBound
# define crc32 z_crc32 # define uncompress z_uncompress
# define get_crc_table z_get_crc_table # define adler32 z_adler32
# define crc32 z_crc32
# define get_crc_table z_get_crc_table
# define zError z_zError
# define Byte z_Byte # define alloc_func z_alloc_func
# define uInt z_uInt # define free_func z_free_func
# define uLong z_uLong # define in_func z_in_func
# define Bytef z_Bytef # define out_func z_out_func
# define charf z_charf # define Byte z_Byte
# define intf z_intf # define uInt z_uInt
# define uIntf z_uIntf # define uLong z_uLong
# define uLongf z_uLongf # define Bytef z_Bytef
# define voidpf z_voidpf # define charf z_charf
# define voidp z_voidp # define intf z_intf
# define uIntf z_uIntf
# define uLongf z_uLongf
# define voidpf z_voidpf
# define voidp z_voidp
#endif #endif
#if defined(__MSDOS__) && !defined(MSDOS) #if defined(__MSDOS__) && !defined(MSDOS)
...@@ -61,8 +68,10 @@ ...@@ -61,8 +68,10 @@
#if defined(_WINDOWS) && !defined(WINDOWS) #if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS # define WINDOWS
#endif #endif
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
# define WIN32 # ifndef WIN32
# define WIN32
# endif
#endif #endif
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
...@@ -281,7 +290,7 @@ typedef uLong FAR uLongf; ...@@ -281,7 +290,7 @@ typedef uLong FAR uLongf;
# ifdef VMS # ifdef VMS
# include <unixio.h> /* for off_t */ # include <unixio.h> /* for off_t */
# endif # endif
# define z_off_t off_t # define z_off_t off_t
#endif #endif
#ifndef SEEK_SET #ifndef SEEK_SET
# define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_SET 0 /* Seek from beginning of file. */
...@@ -289,11 +298,11 @@ typedef uLong FAR uLongf; ...@@ -289,11 +298,11 @@ typedef uLong FAR uLongf;
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif #endif
#ifndef z_off_t #ifndef z_off_t
# define z_off_t long # define z_off_t long
#endif #endif
#if defined(__OS400__) #if defined(__OS400__)
#define NO_vsnprintf # define NO_vsnprintf
#endif #endif
#if defined(__MVS__) #if defined(__MVS__)
......
/* zconf.h -- configuration of the zlib compression library /* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -13,43 +13,50 @@ ...@@ -13,43 +13,50 @@
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
*/ */
#ifdef Z_PREFIX #ifdef Z_PREFIX
# define deflateInit_ z_deflateInit_ # define deflateInit_ z_deflateInit_
# define deflate z_deflate # define deflate z_deflate
# define deflateEnd z_deflateEnd # define deflateEnd z_deflateEnd
# define inflateInit_ z_inflateInit_ # define inflateInit_ z_inflateInit_
# define inflate z_inflate # define inflate z_inflate
# define inflateEnd z_inflateEnd # define inflateEnd z_inflateEnd
# define deflateInit2_ z_deflateInit2_ # define deflateInit2_ z_deflateInit2_
# define deflateSetDictionary z_deflateSetDictionary # define deflateSetDictionary z_deflateSetDictionary
# define deflateCopy z_deflateCopy # define deflateCopy z_deflateCopy
# define deflateReset z_deflateReset # define deflateReset z_deflateReset
# define deflatePrime z_deflatePrime # define deflateParams z_deflateParams
# define deflateParams z_deflateParams # define deflateBound z_deflateBound
# define deflateBound z_deflateBound # define deflatePrime z_deflatePrime
# define inflateInit2_ z_inflateInit2_ # define inflateInit2_ z_inflateInit2_
# define inflateSetDictionary z_inflateSetDictionary # define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync # define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint # define inflateSyncPoint z_inflateSyncPoint
# define inflateCopy z_inflateCopy # define inflateCopy z_inflateCopy
# define inflateReset z_inflateReset # define inflateReset z_inflateReset
# define compress z_compress # define inflateBack z_inflateBack
# define compress2 z_compress2 # define inflateBackEnd z_inflateBackEnd
# define compressBound z_compressBound # define compress z_compress
# define uncompress z_uncompress # define compress2 z_compress2
# define adler32 z_adler32 # define compressBound z_compressBound
# define crc32 z_crc32 # define uncompress z_uncompress
# define get_crc_table z_get_crc_table # define adler32 z_adler32
# define crc32 z_crc32
# define get_crc_table z_get_crc_table
# define zError z_zError
# define Byte z_Byte # define alloc_func z_alloc_func
# define uInt z_uInt # define free_func z_free_func
# define uLong z_uLong # define in_func z_in_func
# define Bytef z_Bytef # define out_func z_out_func
# define charf z_charf # define Byte z_Byte
# define intf z_intf # define uInt z_uInt
# define uIntf z_uIntf # define uLong z_uLong
# define uLongf z_uLongf # define Bytef z_Bytef
# define voidpf z_voidpf # define charf z_charf
# define voidp z_voidp # define intf z_intf
# define uIntf z_uIntf
# define uLongf z_uLongf
# define voidpf z_voidpf
# define voidp z_voidp
#endif #endif
#if defined(__MSDOS__) && !defined(MSDOS) #if defined(__MSDOS__) && !defined(MSDOS)
...@@ -61,8 +68,10 @@ ...@@ -61,8 +68,10 @@
#if defined(_WINDOWS) && !defined(WINDOWS) #if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS # define WINDOWS
#endif #endif
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
# define WIN32 # ifndef WIN32
# define WIN32
# endif
#endif #endif
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
...@@ -281,7 +290,7 @@ typedef uLong FAR uLongf; ...@@ -281,7 +290,7 @@ typedef uLong FAR uLongf;
# ifdef VMS # ifdef VMS
# include <unixio.h> /* for off_t */ # include <unixio.h> /* for off_t */
# endif # endif
# define z_off_t off_t # define z_off_t off_t
#endif #endif
#ifndef SEEK_SET #ifndef SEEK_SET
# define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_SET 0 /* Seek from beginning of file. */
...@@ -289,11 +298,11 @@ typedef uLong FAR uLongf; ...@@ -289,11 +298,11 @@ typedef uLong FAR uLongf;
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif #endif
#ifndef z_off_t #ifndef z_off_t
# define z_off_t long # define z_off_t long
#endif #endif
#if defined(__OS400__) #if defined(__OS400__)
#define NO_vsnprintf # define NO_vsnprintf
#endif #endif
#if defined(__MVS__) #if defined(__MVS__)
......
.TH ZLIB 3 "17 November 2003" .TH ZLIB 3 "18 July 2005"
.SH NAME .SH NAME
zlib \- compression/decompression library zlib \- compression/decompression library
.SH SYNOPSIS .SH SYNOPSIS
...@@ -133,8 +133,8 @@ before asking for help. ...@@ -133,8 +133,8 @@ before asking for help.
Send questions and/or comments to zlib@gzip.org, Send questions and/or comments to zlib@gzip.org,
or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). or (for the Windows DLL version) to Gilles Vollant (info@winimage.com).
.SH AUTHORS .SH AUTHORS
Version 1.2.1 Version 1.2.3
Copyright (C) 1995-2003 Jean-loup Gailly (jloup@gzip.org) Copyright (C) 1995-2005 Jean-loup Gailly (jloup@gzip.org)
and Mark Adler (madler@alumni.caltech.edu). and Mark Adler (madler@alumni.caltech.edu).
.LP .LP
This software is provided "as-is," This software is provided "as-is,"
......
/* zlib.h -- interface of the 'zlib' general purpose compression library /* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.1, November 17th, 2003 version 1.2.3, July 18th, 2005
Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages warranty. In no event will the authors be held liable for any damages
...@@ -37,8 +37,8 @@ ...@@ -37,8 +37,8 @@
extern "C" { extern "C" {
#endif #endif
#define ZLIB_VERSION "1.2.1" #define ZLIB_VERSION "1.2.3"
#define ZLIB_VERNUM 0x1210 #define ZLIB_VERNUM 0x1230
/* /*
The 'zlib' compression library provides in-memory compression and The 'zlib' compression library provides in-memory compression and
...@@ -53,24 +53,22 @@ extern "C" { ...@@ -53,24 +53,22 @@ extern "C" {
application must provide more input and/or consume the output application must provide more input and/or consume the output
(providing more output space) before each call. (providing more output space) before each call.
The compressed data format used by the in-memory functions is the zlib The compressed data format used by default by the in-memory functions is
format, which is a zlib wrapper documented in RFC 1950, wrapped around a the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
deflate stream, which is itself documented in RFC 1951. around a deflate stream, which is itself documented in RFC 1951.
The library also supports reading and writing files in gzip (.gz) format The library also supports reading and writing files in gzip (.gz) format
with an interface similar to that of stdio using the functions that start with an interface similar to that of stdio using the functions that start
with "gz". The gzip format is different from the zlib format. gzip is a with "gz". The gzip format is different from the zlib format. gzip is a
gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
This library can optionally read and write gzip streams in memory as well.
The zlib format was designed to be compact and fast for use in memory The zlib format was designed to be compact and fast for use in memory
and on communications channels. The gzip format was designed for single- and on communications channels. The gzip format was designed for single-
file compression on file systems, has a larger header than zlib to maintain file compression on file systems, has a larger header than zlib to maintain
directory information, and uses a different, slower check method than zlib. directory information, and uses a different, slower check method than zlib.
This library does not provide any functions to write gzip files in memory.
However such functions could be easily written using zlib's deflate function,
the documentation in the gzip RFC, and the examples in gzio.c.
The library does not install any signal handler. The decoder checks The library does not install any signal handler. The decoder checks
the consistency of the compressed data, so the library should never the consistency of the compressed data, so the library should never
crash even in case of corrupted input. crash even in case of corrupted input.
...@@ -97,7 +95,7 @@ typedef struct z_stream_s { ...@@ -97,7 +95,7 @@ typedef struct z_stream_s {
free_func zfree; /* used to free the internal state */ free_func zfree; /* used to free the internal state */
voidpf opaque; /* private data object passed to zalloc and zfree */ voidpf opaque; /* private data object passed to zalloc and zfree */
int data_type; /* best guess about the data type: ascii or binary */ int data_type; /* best guess about the data type: binary or text */
uLong adler; /* adler32 value of the uncompressed data */ uLong adler; /* adler32 value of the uncompressed data */
uLong reserved; /* reserved for future use */ uLong reserved; /* reserved for future use */
} z_stream; } z_stream;
...@@ -105,6 +103,29 @@ typedef struct z_stream_s { ...@@ -105,6 +103,29 @@ typedef struct z_stream_s {
typedef z_stream FAR *z_streamp; typedef z_stream FAR *z_streamp;
/* /*
gzip header information passed to and from zlib routines. See RFC 1952
for more details on the meanings of these fields.
*/
typedef struct gz_header_s {
int text; /* true if compressed data believed to be text */
uLong time; /* modification time */
int xflags; /* extra flags (not used when writing a gzip file) */
int os; /* operating system */
Bytef *extra; /* pointer to extra field or Z_NULL if none */
uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
uInt extra_max; /* space at extra (only when reading header) */
Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
uInt name_max; /* space at name (only when reading header) */
Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
uInt comm_max; /* space at comment (only when reading header) */
int hcrc; /* true if there was or will be a header crc */
int done; /* true when done reading gzip header (not used
when writing a gzip file) */
} gz_header;
typedef gz_header FAR *gz_headerp;
/*
The application must update next_in and avail_in when avail_in has The application must update next_in and avail_in when avail_in has
dropped to zero. It must update next_out and avail_out when avail_out dropped to zero. It must update next_out and avail_out when avail_out
has dropped to zero. The application must initialize zalloc, zfree and has dropped to zero. The application must initialize zalloc, zfree and
...@@ -168,11 +189,13 @@ typedef z_stream FAR *z_streamp; ...@@ -168,11 +189,13 @@ typedef z_stream FAR *z_streamp;
#define Z_FILTERED 1 #define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2 #define Z_HUFFMAN_ONLY 2
#define Z_RLE 3 #define Z_RLE 3
#define Z_FIXED 4
#define Z_DEFAULT_STRATEGY 0 #define Z_DEFAULT_STRATEGY 0
/* compression strategy; see deflateInit2() below for details */ /* compression strategy; see deflateInit2() below for details */
#define Z_BINARY 0 #define Z_BINARY 0
#define Z_ASCII 1 #define Z_TEXT 1
#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
#define Z_UNKNOWN 2 #define Z_UNKNOWN 2
/* Possible values of the data_type field (though see inflate()) */ /* Possible values of the data_type field (though see inflate()) */
...@@ -246,6 +269,10 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); ...@@ -246,6 +269,10 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
and with zero avail_out, it must be called again after making room in the and with zero avail_out, it must be called again after making room in the
output buffer because there might be more output pending. output buffer because there might be more output pending.
Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
decide how much data to accumualte before producing output, in order to
maximize compression.
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
flushed to the output buffer and the output is aligned on a byte boundary, so flushed to the output buffer and the output is aligned on a byte boundary, so
that the decompressor can get all input data available so far. (In particular that the decompressor can get all input data available so far. (In particular
...@@ -257,7 +284,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); ...@@ -257,7 +284,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
Z_SYNC_FLUSH, and the compression state is reset so that decompression can Z_SYNC_FLUSH, and the compression state is reset so that decompression can
restart from this point if previous compressed data has been damaged or if restart from this point if previous compressed data has been damaged or if
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
the compression. compression.
If deflate returns with avail_out == 0, this function must be called again If deflate returns with avail_out == 0, this function must be called again
with the same value of the flush parameter and more output space (updated with the same value of the flush parameter and more output space (updated
...@@ -282,8 +309,8 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); ...@@ -282,8 +309,8 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
deflate() sets strm->adler to the adler32 checksum of all input read deflate() sets strm->adler to the adler32 checksum of all input read
so far (that is, total_in bytes). so far (that is, total_in bytes).
deflate() may update data_type if it can make a good guess about deflate() may update strm->data_type if it can make a good guess about
the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
binary. This field is only for information purposes and does not affect binary. This field is only for information purposes and does not affect
the compression algorithm in any manner. the compression algorithm in any manner.
...@@ -365,11 +392,11 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); ...@@ -365,11 +392,11 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
output as possible to the output buffer. Z_BLOCK requests that inflate() stop output as possible to the output buffer. Z_BLOCK requests that inflate() stop
if and when it get to the next deflate block boundary. When decoding the zlib if and when it gets to the next deflate block boundary. When decoding the
or gzip format, this will cause inflate() to return immediately after the zlib or gzip format, this will cause inflate() to return immediately after
header and before the first block. When doing a raw inflate, inflate() will the header and before the first block. When doing a raw inflate, inflate()
go ahead and process the first block, and will return when it gets to the end will go ahead and process the first block, and will return when it gets to
of that block, or when it runs out of data. the end of that block, or when it runs out of data.
The Z_BLOCK option assists in appending to or combining deflate streams. The Z_BLOCK option assists in appending to or combining deflate streams.
Also to assist in this, on return inflate() will set strm->data_type to the Also to assist in this, on return inflate() will set strm->data_type to the
...@@ -401,7 +428,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); ...@@ -401,7 +428,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
because Z_BLOCK is used. because Z_BLOCK is used.
If a preset dictionary is needed after this call (see inflateSetDictionary If a preset dictionary is needed after this call (see inflateSetDictionary
below), inflate sets strm-adler to the adler32 checksum of the dictionary below), inflate sets strm->adler to the adler32 checksum of the dictionary
chosen by the compressor and returns Z_NEED_DICT; otherwise it sets chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
strm->adler to the adler32 checksum of all output produced so far (that is, strm->adler to the adler32 checksum of all output produced so far (that is,
total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
...@@ -478,7 +505,8 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, ...@@ -478,7 +505,8 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
16 to windowBits to write a simple gzip header and trailer around the 16 to windowBits to write a simple gzip header and trailer around the
compressed data instead of a zlib wrapper. The gzip header will have no compressed data instead of a zlib wrapper. The gzip header will have no
file name, no extra data, no comment, no modification time (set to zero), file name, no extra data, no comment, no modification time (set to zero),
no header crc, and the operating system will be set to 255 (unknown). no header crc, and the operating system will be set to 255 (unknown). If a
gzip stream is being written, strm->adler is a crc32 instead of an adler32.
The memLevel parameter specifies how much memory should be allocated The memLevel parameter specifies how much memory should be allocated
for the internal compression state. memLevel=1 uses minimum memory but for the internal compression state. memLevel=1 uses minimum memory but
...@@ -497,7 +525,9 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, ...@@ -497,7 +525,9 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
parameter only affects the compression ratio but not the correctness of the parameter only affects the compression ratio but not the correctness of the
compressed output even if it is not set appropriately. compressed output even if it is not set appropriately. Z_FIXED prevents the
use of dynamic Huffman codes, allowing for a simpler decoder for special
applications.
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
...@@ -526,7 +556,9 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, ...@@ -526,7 +556,9 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
deflateInit or deflateInit2, a part of the dictionary may in effect be deflateInit or deflateInit2, a part of the dictionary may in effect be
discarded, for example if the dictionary is larger than the window size in discarded, for example if the dictionary is larger than the window size in
deflate or deflate2. Thus the strings most likely to be useful should be deflate or deflate2. Thus the strings most likely to be useful should be
put at the end of the dictionary, not at the front. put at the end of the dictionary, not at the front. In addition, the
current implementation of deflate will use at most the window size minus
262 bytes of the provided dictionary.
Upon return of this function, strm->adler is set to the adler32 value Upon return of this function, strm->adler is set to the adler32 value
of the dictionary; the decompressor may later use this value to determine of the dictionary; the decompressor may later use this value to determine
...@@ -592,6 +624,23 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, ...@@ -592,6 +624,23 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
if strm->avail_out was zero. if strm->avail_out was zero.
*/ */
ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
int good_length,
int max_lazy,
int nice_length,
int max_chain));
/*
Fine tune deflate's internal compression parameters. This should only be
used by someone who understands the algorithm used by zlib's deflate for
searching for the best matching string, and even then only by the most
fanatic optimizer trying to squeeze out the last compressed bit for their
specific input data. Read the deflate.c source code for the meaning of the
max_lazy, good_length, nice_length, and max_chain parameters.
deflateTune() can be called after deflateInit() or deflateInit2(), and
returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
*/
ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
uLong sourceLen)); uLong sourceLen));
/* /*
...@@ -617,6 +666,30 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, ...@@ -617,6 +666,30 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
stream state was inconsistent. stream state was inconsistent.
*/ */
ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
gz_headerp head));
/*
deflateSetHeader() provides gzip header information for when a gzip
stream is requested by deflateInit2(). deflateSetHeader() may be called
after deflateInit2() or deflateReset() and before the first call of
deflate(). The text, time, os, extra field, name, and comment information
in the provided gz_header structure are written to the gzip header (xflag is
ignored -- the extra flags are set according to the compression level). The
caller must assure that, if not Z_NULL, name and comment are terminated with
a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
available there. If hcrc is true, a gzip header crc is included. Note that
the current versions of the command-line version of gzip (up through version
1.3.x) do not support header crc's, and will report that it is a "multi-part
gzip file" and give up.
If deflateSetHeader is not used, the default gzip header has text false,
the time set to zero, and os set to 255, with no extra, name, or comment
fields. The gzip header is returned to the default state by deflateReset().
deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*/
/* /*
ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
int windowBits)); int windowBits));
...@@ -649,14 +722,15 @@ ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, ...@@ -649,14 +722,15 @@ ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
windowBits can also be greater than 15 for optional gzip decoding. Add windowBits can also be greater than 15 for optional gzip decoding. Add
32 to windowBits to enable zlib and gzip decoding with automatic header 32 to windowBits to enable zlib and gzip decoding with automatic header
detection, or add 16 to decode only the gzip format (the zlib format will detection, or add 16 to decode only the gzip format (the zlib format will
return a Z_DATA_ERROR). return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
a crc32 instead of an adler32.
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
memLevel). msg is set to null if there is no error message. inflateInit2 is set to null if there is no error message. inflateInit2 does not perform
does not perform any decompression apart from reading the zlib header if any decompression apart from reading the zlib header if present: this will
present: this will be done by inflate(). (So next_in and avail_in may be be done by inflate(). (So next_in and avail_in may be modified, but next_out
modified, but next_out and avail_out are unchanged.) and avail_out are unchanged.)
*/ */
ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
...@@ -664,11 +738,14 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, ...@@ -664,11 +738,14 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
uInt dictLength)); uInt dictLength));
/* /*
Initializes the decompression dictionary from the given uncompressed byte Initializes the decompression dictionary from the given uncompressed byte
sequence. This function must be called immediately after a call of inflate sequence. This function must be called immediately after a call of inflate,
if this call returned Z_NEED_DICT. The dictionary chosen by the compressor if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
can be determined from the adler32 value returned by this call of can be determined from the adler32 value returned by that call of inflate.
inflate. The compressor and decompressor must use exactly the same The compressor and decompressor must use exactly the same dictionary (see
dictionary (see deflateSetDictionary). deflateSetDictionary). For raw inflate, this function can be called
immediately after inflateInit2() or inflateReset() and before any call of
inflate() to set the dictionary. The application must insure that the
dictionary that was used for compression is provided.
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
parameter is invalid (such as NULL dictionary) or the stream state is parameter is invalid (such as NULL dictionary) or the stream state is
...@@ -719,8 +796,64 @@ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); ...@@ -719,8 +796,64 @@ ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
stream state was inconsistent (such as zalloc or state being NULL). stream state was inconsistent (such as zalloc or state being NULL).
*/ */
ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
int bits,
int value));
/*
This function inserts bits in the inflate input stream. The intent is
that this function is used to start inflating at a bit position in the
middle of a byte. The provided bits will be used before any bytes are used
from next_in. This function should only be used with raw inflate, and
should be used before the first inflate() call after inflateInit2() or
inflateReset(). bits must be less than or equal to 16, and that many of the
least significant bits of value will be inserted in the input.
inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*/
ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
gz_headerp head));
/* /*
ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits, inflateGetHeader() requests that gzip header information be stored in the
provided gz_header structure. inflateGetHeader() may be called after
inflateInit2() or inflateReset(), and before the first call of inflate().
As inflate() processes the gzip stream, head->done is zero until the header
is completed, at which time head->done is set to one. If a zlib stream is
being decoded, then head->done is set to -1 to indicate that there will be
no gzip header information forthcoming. Note that Z_BLOCK can be used to
force inflate() to return immediately after header processing is complete
and before any actual data is decompressed.
The text, time, xflags, and os fields are filled in with the gzip header
contents. hcrc is set to true if there is a header CRC. (The header CRC
was valid if done is set to one.) If extra is not Z_NULL, then extra_max
contains the maximum number of bytes to write to extra. Once done is true,
extra_len contains the actual extra field length, and extra contains the
extra field, or that field truncated if extra_max is less than extra_len.
If name is not Z_NULL, then up to name_max characters are written there,
terminated with a zero unless the length is greater than name_max. If
comment is not Z_NULL, then up to comm_max characters are written there,
terminated with a zero unless the length is greater than comm_max. When
any of extra, name, or comment are not Z_NULL and the respective field is
not present in the header, then that field is set to Z_NULL to signal its
absence. This allows the use of deflateSetHeader() with the returned
structure to duplicate the header. However if those fields are set to
allocated memory, then the application will need to save those pointers
elsewhere so that they can be eventually freed.
If inflateGetHeader is not used, then the header information is simply
discarded. The header is always checked for validity, including the header
CRC if present. inflateReset() will reset the process to discard the header
information. The application would need to call inflateGetHeader() again to
retrieve the header from the next gzip stream.
inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
stream state was inconsistent.
*/
/*
ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
unsigned char FAR *window)); unsigned char FAR *window));
Initialize the internal stream state for decompression using inflateBack() Initialize the internal stream state for decompression using inflateBack()
...@@ -744,7 +877,7 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits, ...@@ -744,7 +877,7 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_stream FAR *strm, int windowBits,
typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm, ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
in_func in, void FAR *in_desc, in_func in, void FAR *in_desc,
out_func out, void FAR *out_desc)); out_func out, void FAR *out_desc));
/* /*
...@@ -813,7 +946,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm, ...@@ -813,7 +946,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_stream FAR *strm,
that inflateBack() cannot return Z_OK. that inflateBack() cannot return Z_OK.
*/ */
ZEXTERN int ZEXPORT inflateBackEnd OF((z_stream FAR *strm)); ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
/* /*
All memory allocated by inflateBackInit() is freed. All memory allocated by inflateBackInit() is freed.
...@@ -1087,6 +1220,12 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); ...@@ -1087,6 +1220,12 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file));
input stream, otherwise zero. input stream, otherwise zero.
*/ */
ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
/*
Returns 1 if file is being read directly without decompression, otherwise
zero.
*/
ZEXTERN int ZEXPORT gzclose OF((gzFile file)); ZEXTERN int ZEXPORT gzclose OF((gzFile file));
/* /*
Flushes all pending output if necessary, closes the compressed file Flushes all pending output if necessary, closes the compressed file
...@@ -1119,7 +1258,6 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); ...@@ -1119,7 +1258,6 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
*/ */
ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
/* /*
Update a running Adler-32 checksum with the bytes buf[0..len-1] and Update a running Adler-32 checksum with the bytes buf[0..len-1] and
return the updated checksum. If buf is NULL, this function returns return the updated checksum. If buf is NULL, this function returns
...@@ -1135,12 +1273,21 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); ...@@ -1135,12 +1273,21 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
if (adler != original_adler) error(); if (adler != original_adler) error();
*/ */
ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
z_off_t len2));
/*
Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
*/
ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
/* /*
Update a running crc with the bytes buf[0..len-1] and return the updated Update a running CRC-32 with the bytes buf[0..len-1] and return the
crc. If buf is NULL, this function returns the required initial value updated CRC-32. If buf is NULL, this function returns the required initial
for the crc. Pre- and post-conditioning (one's complement) is performed value for the for the crc. Pre- and post-conditioning (one's complement) is
within this function so it shouldn't be done by the application. performed within this function so it shouldn't be done by the application.
Usage example: Usage example:
uLong crc = crc32(0L, Z_NULL, 0); uLong crc = crc32(0L, Z_NULL, 0);
...@@ -1151,6 +1298,16 @@ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); ...@@ -1151,6 +1298,16 @@ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
if (crc != original_crc) error(); if (crc != original_crc) error();
*/ */
ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
/*
Combine two CRC-32 check values into one. For two sequences of bytes,
seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
len2.
*/
/* various hacks, don't look :) */ /* various hacks, don't look :) */
...@@ -1167,7 +1324,7 @@ ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, ...@@ -1167,7 +1324,7 @@ ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
int stream_size)); int stream_size));
ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
const char *version, int stream_size)); const char *version, int stream_size));
ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits, ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
unsigned char FAR *window, unsigned char FAR *window,
const char *version, const char *version,
int stream_size)); int stream_size));
...@@ -1189,7 +1346,7 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits, ...@@ -1189,7 +1346,7 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_stream FAR *strm, int windowBits,
struct internal_state {int dummy;}; /* hack for buggy compilers */ struct internal_state {int dummy;}; /* hack for buggy compilers */
#endif #endif
ZEXTERN const char * ZEXPORT zError OF((int err)); ZEXTERN const char * ZEXPORT zError OF((int));
ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
......
/* zutil.c -- target dependent utility functions for the compression library /* zutil.c -- target dependent utility functions for the compression library
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -11,10 +11,6 @@ ...@@ -11,10 +11,6 @@
struct internal_state {int dummy;}; /* for buggy compilers */ struct internal_state {int dummy;}; /* for buggy compilers */
#endif #endif
#ifndef STDC
extern void exit OF((int));
#endif
const char * const z_errmsg[10] = { const char * const z_errmsg[10] = {
"need dictionary", /* Z_NEED_DICT 2 */ "need dictionary", /* Z_NEED_DICT 2 */
"stream end", /* Z_STREAM_END 1 */ "stream end", /* Z_STREAM_END 1 */
...@@ -78,38 +74,38 @@ uLong ZEXPORT zlibCompileFlags() ...@@ -78,38 +74,38 @@ uLong ZEXPORT zlibCompileFlags()
flags += 1 << 13; flags += 1 << 13;
#endif #endif
#ifdef NO_GZCOMPRESS #ifdef NO_GZCOMPRESS
flags += 1 << 16; flags += 1L << 16;
#endif #endif
#ifdef NO_GZIP #ifdef NO_GZIP
flags += 1 << 17; flags += 1L << 17;
#endif #endif
#ifdef PKZIP_BUG_WORKAROUND #ifdef PKZIP_BUG_WORKAROUND
flags += 1 << 20; flags += 1L << 20;
#endif #endif
#ifdef FASTEST #ifdef FASTEST
flags += 1 << 21; flags += 1L << 21;
#endif #endif
#ifdef STDC #ifdef STDC
# ifdef NO_vsnprintf # ifdef NO_vsnprintf
flags += 1 << 25; flags += 1L << 25;
# ifdef HAS_vsprintf_void # ifdef HAS_vsprintf_void
flags += 1 << 26; flags += 1L << 26;
# endif # endif
# else # else
# ifdef HAS_vsnprintf_void # ifdef HAS_vsnprintf_void
flags += 1 << 26; flags += 1L << 26;
# endif # endif
# endif # endif
#else #else
flags += 1 << 24; flags += 1L << 24;
# ifdef NO_snprintf # ifdef NO_snprintf
flags += 1 << 25; flags += 1L << 25;
# ifdef HAS_sprintf_void # ifdef HAS_sprintf_void
flags += 1 << 26; flags += 1L << 26;
# endif # endif
# else # else
# ifdef HAS_snprintf_void # ifdef HAS_snprintf_void
flags += 1 << 26; flags += 1L << 26;
# endif # endif
# endif # endif
#endif #endif
...@@ -141,7 +137,10 @@ const char * ZEXPORT zError(err) ...@@ -141,7 +137,10 @@ const char * ZEXPORT zError(err)
} }
#if defined(_WIN32_WCE) #if defined(_WIN32_WCE)
/* does not exist on WCE */ /* The Microsoft C Run-Time Library for Windows CE doesn't have
* errno. We define it as a global variable to simplify porting.
* Its value is always 0 and should not be used.
*/
int errno = 0; int errno = 0;
#endif #endif
......
/* zutil.h -- internal interface and configuration of the compression library /* zutil.h -- internal interface and configuration of the compression library
* Copyright (C) 1995-2003 Jean-loup Gailly. * Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
...@@ -17,14 +17,26 @@ ...@@ -17,14 +17,26 @@
#include "zlib.h" #include "zlib.h"
#ifdef STDC #ifdef STDC
# include <stddef.h> # ifndef _WIN32_WCE
# include <stddef.h>
# endif
# include <string.h> # include <string.h>
# include <stdlib.h> # include <stdlib.h>
#endif #endif
#ifdef NO_ERRNO_H #ifdef NO_ERRNO_H
# ifdef _WIN32_WCE
/* The Microsoft C Run-Time Library for Windows CE doesn't have
* errno. We define it as a global variable to simplify porting.
* Its value is always 0 and should not be used. We rename it to
* avoid conflict with other libraries that use the same workaround.
*/
# define errno z_errno
# endif
extern int errno; extern int errno;
#else #else
# include <errno.h> # ifndef _WIN32_WCE
# include <errno.h>
# endif
#endif #endif
#ifndef local #ifndef local
...@@ -105,6 +117,9 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ ...@@ -105,6 +117,9 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
#ifdef OS2 #ifdef OS2
# define OS_CODE 0x06 # define OS_CODE 0x06
# ifdef M_I86
#include <malloc.h>
# endif
#endif #endif
#if defined(MACOS) || defined(TARGET_OS_MAC) #if defined(MACOS) || defined(TARGET_OS_MAC)
...@@ -189,12 +204,8 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ ...@@ -189,12 +204,8 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
# define NO_vsnprintf # define NO_vsnprintf
# endif # endif
#endif #endif
#ifdef VMS
#ifdef HAVE_STRERROR # define NO_vsnprintf
extern char *strerror OF((int));
# define zstrerror(errnum) strerror(errnum)
#else
# define zstrerror(errnum) ""
#endif #endif
#if defined(pyr) #if defined(pyr)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment