1 package IO::Uncompress::Inflate ;
8 use IO::Compress::Base::Common 2.011 qw(:Status createSelfTiedObject);
9 use IO::Compress::Zlib::Constants 2.011 ;
11 use IO::Uncompress::RawInflate 2.011 ;
14 our ($VERSION, @ISA, @EXPORT_OK, %EXPORT_TAGS, $InflateError);
19 @ISA = qw( Exporter IO::Uncompress::RawInflate );
20 @EXPORT_OK = qw( $InflateError inflate ) ;
21 %EXPORT_TAGS = %IO::Uncompress::RawInflate::DEFLATE_CONSTANTS ;
22 push @{ $EXPORT_TAGS{all} }, @EXPORT_OK ;
23 Exporter::export_ok_tags('all');
29 my $obj = createSelfTiedObject($class, \$InflateError);
31 $obj->_create(undef, 0, @_);
36 my $obj = createSelfTiedObject(undef, \$InflateError);
37 return $obj->_inf(@_);
50 # gunzip always needs adler32
51 $got->value('ADLER32' => 1);
61 $self->smartReadExact(\$magic, ZLIB_HEADER_SIZE);
63 *$self->{HeaderPending} = $magic ;
65 return $self->HeaderError("Header size is " .
66 ZLIB_HEADER_SIZE . " bytes")
67 if length $magic != ZLIB_HEADER_SIZE;
69 #return $self->HeaderError("CRC mismatch.")
71 if ! $self->isZlibMagic($magic) ;
73 *$self->{Type} = 'rfc1950';
82 return $self->_readDeflateHeader($magic) ;
90 my $ADLER32 = unpack("N", $trailer) ;
91 *$self->{Info}{ADLER32} = $ADLER32;
92 return $self->TrailerError("CRC mismatch")
93 if *$self->{Strict} && $ADLER32 != *$self->{Uncomp}->adler32() ;
106 if length $buffer < ZLIB_HEADER_SIZE ;
108 my $hdr = unpack("n", $buffer) ;
109 #return 0 if $hdr % 31 != 0 ;
110 return $self->HeaderError("CRC mismatch.")
113 my ($CMF, $FLG) = unpack "C C", $buffer;
114 my $cm = bits($CMF, ZLIB_CMF_CM_OFFSET, ZLIB_CMF_CM_BITS) ;
116 # Only Deflate supported
117 return $self->HeaderError("Not Deflate (CM is $cm)")
118 if $cm != ZLIB_CMF_CM_DEFLATED ;
120 # Max window value is 7 for Deflate.
121 my $cinfo = bits($CMF, ZLIB_CMF_CINFO_OFFSET, ZLIB_CMF_CINFO_BITS) ;
122 return $self->HeaderError("CINFO > " . ZLIB_CMF_CINFO_MAX .
123 " (CINFO is $cinfo)")
124 if $cinfo > ZLIB_CMF_CINFO_MAX ;
135 ($data >> $offset ) & $mask & 0xFF ;
139 sub _readDeflateHeader
141 my ($self, $buffer) = @_ ;
144 # $self->smartReadExact(\$buffer, ZLIB_HEADER_SIZE);
146 # *$self->{HeaderPending} = $buffer ;
148 # return $self->HeaderError("Header size is " .
149 # ZLIB_HEADER_SIZE . " bytes")
150 # if length $buffer != ZLIB_HEADER_SIZE;
152 # return $self->HeaderError("CRC mismatch.")
153 # if ! isZlibMagic($buffer) ;
156 my ($CMF, $FLG) = unpack "C C", $buffer;
157 my $FDICT = bits($FLG, ZLIB_FLG_FDICT_OFFSET, ZLIB_FLG_FDICT_BITS ),
159 my $cm = bits($CMF, ZLIB_CMF_CM_OFFSET, ZLIB_CMF_CM_BITS) ;
160 $cm == ZLIB_CMF_CM_DEFLATED
161 or return $self->HeaderError("Not Deflate (CM is $cm)") ;
165 $self->smartReadExact(\$buffer, ZLIB_FDICT_SIZE)
166 or return $self->TruncatedHeader("FDICT");
168 $DICTID = unpack("N", $buffer) ;
171 *$self->{Type} = 'rfc1950';
175 'FingerprintLength' => ZLIB_HEADER_SIZE,
176 'HeaderLength' => ZLIB_HEADER_SIZE,
177 'TrailerLength' => ZLIB_TRAILER_SIZE,
181 CM => bits($CMF, ZLIB_CMF_CM_OFFSET, ZLIB_CMF_CM_BITS ),
182 CINFO => bits($CMF, ZLIB_CMF_CINFO_OFFSET, ZLIB_CMF_CINFO_BITS ),
184 FCHECK => bits($FLG, ZLIB_FLG_FCHECK_OFFSET, ZLIB_FLG_FCHECK_BITS),
185 FDICT => bits($FLG, ZLIB_FLG_FDICT_OFFSET, ZLIB_FLG_FDICT_BITS ),
186 FLEVEL => bits($FLG, ZLIB_FLG_LEVEL_OFFSET, ZLIB_FLG_LEVEL_BITS ),
202 IO::Uncompress::Inflate - Read RFC 1950 files/buffers
206 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
208 my $status = inflate $input => $output [,OPTS]
209 or die "inflate failed: $InflateError\n";
211 my $z = new IO::Uncompress::Inflate $input [OPTS]
212 or die "inflate failed: $InflateError\n";
214 $status = $z->read($buffer)
215 $status = $z->read($buffer, $length)
216 $status = $z->read($buffer, $length, $offset)
217 $line = $z->getline()
222 $status = $z->inflateSync()
224 $data = $z->trailingData()
225 $status = $z->nextStream()
226 $data = $z->getHeaderInfo()
228 $z->seek($position, $whence)
240 read($z, $buffer, $length);
241 read($z, $buffer, $length, $offset);
243 seek($z, $position, $whence)
251 This module provides a Perl interface that allows the reading of
252 files/buffers that conform to RFC 1950.
254 For writing RFC 1950 files/buffers, see the companion module IO::Compress::Deflate.
256 =head1 Functional Interface
258 A top-level function, C<inflate>, is provided to carry out
259 "one-shot" uncompression between buffers and/or files. For finer
260 control over the uncompression process, see the L</"OO Interface">
263 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
265 inflate $input => $output [,OPTS]
266 or die "inflate failed: $InflateError\n";
268 The functional interface needs Perl5.005 or better.
270 =head2 inflate $input => $output [, OPTS]
272 C<inflate> expects at least two parameters, C<$input> and C<$output>.
274 =head3 The C<$input> parameter
276 The parameter, C<$input>, is used to define the source of
279 It can take one of the following forms:
285 If the C<$input> parameter is a simple scalar, it is assumed to be a
286 filename. This file will be opened for reading and the input data
287 will be read from it.
291 If the C<$input> parameter is a filehandle, the input data will be
293 The string '-' can be used as an alias for standard input.
295 =item A scalar reference
297 If C<$input> is a scalar reference, the input data will be read
300 =item An array reference
302 If C<$input> is an array reference, each element in the array must be a
305 The input data will be read from each file in turn.
307 The complete array will be walked to ensure that it only
308 contains valid filenames before any data is uncompressed.
310 =item An Input FileGlob string
312 If C<$input> is a string that is delimited by the characters "<" and ">"
313 C<inflate> will assume that it is an I<input fileglob string>. The
314 input is the list of files that match the fileglob.
316 If the fileglob does not match any files ...
318 See L<File::GlobMapper|File::GlobMapper> for more details.
322 If the C<$input> parameter is any other type, C<undef> will be returned.
324 =head3 The C<$output> parameter
326 The parameter C<$output> is used to control the destination of the
327 uncompressed data. This parameter can take one of these forms.
333 If the C<$output> parameter is a simple scalar, it is assumed to be a
334 filename. This file will be opened for writing and the uncompressed
335 data will be written to it.
339 If the C<$output> parameter is a filehandle, the uncompressed data
340 will be written to it.
341 The string '-' can be used as an alias for standard output.
343 =item A scalar reference
345 If C<$output> is a scalar reference, the uncompressed data will be
346 stored in C<$$output>.
348 =item An Array Reference
350 If C<$output> is an array reference, the uncompressed data will be
351 pushed onto the array.
353 =item An Output FileGlob
355 If C<$output> is a string that is delimited by the characters "<" and ">"
356 C<inflate> will assume that it is an I<output fileglob string>. The
357 output is the list of files that match the fileglob.
359 When C<$output> is an fileglob string, C<$input> must also be a fileglob
360 string. Anything else is an error.
364 If the C<$output> parameter is any other type, C<undef> will be returned.
368 When C<$input> maps to multiple compressed files/buffers and C<$output> is
369 a single file/buffer, after uncompression C<$output> will contain a
370 concatenation of all the uncompressed data from each of the input
373 =head2 Optional Parameters
375 Unless specified below, the optional parameters for C<inflate>,
376 C<OPTS>, are the same as those used with the OO interface defined in the
377 L</"Constructor Options"> section below.
381 =item C<< AutoClose => 0|1 >>
383 This option applies to any input or output data streams to
384 C<inflate> that are filehandles.
386 If C<AutoClose> is specified, and the value is true, it will result in all
387 input and/or output filehandles being closed once C<inflate> has
390 This parameter defaults to 0.
392 =item C<< BinModeOut => 0|1 >>
394 When writing to a file or filehandle, set C<binmode> before writing to the
399 =item C<< Append => 0|1 >>
403 =item C<< MultiStream => 0|1 >>
405 If the input file/buffer contains multiple compressed data streams, this
406 option will uncompress the whole lot as a single data stream.
410 =item C<< TrailingData => $scalar >>
412 Returns the data, if any, that is present immediately after the compressed
413 data stream once uncompression is complete.
415 This option can be used when there is useful information immediately
416 following the compressed data stream, and you don't know the length of the
417 compressed data stream.
419 If the input is a buffer, C<trailingData> will return everything from the
420 end of the compressed data stream to the end of the buffer.
422 If the input is a filehandle, C<trailingData> will return the data that is
423 left in the filehandle input buffer once the end of the compressed data
424 stream has been reached. You can then use the filehandle to read the rest
427 Don't bother using C<trailingData> if the input is a filename.
429 If you know the length of the compressed data stream before you start
430 uncompressing, you can avoid having to use C<trailingData> by setting the
431 C<InputLength> option.
437 To read the contents of the file C<file1.txt.1950> and write the
438 compressed data to the file C<file1.txt>.
442 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
444 my $input = "file1.txt.1950";
445 my $output = "file1.txt";
446 inflate $input => $output
447 or die "inflate failed: $InflateError\n";
449 To read from an existing Perl filehandle, C<$input>, and write the
450 uncompressed data to a buffer, C<$buffer>.
454 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
457 my $input = new IO::File "<file1.txt.1950"
458 or die "Cannot open 'file1.txt.1950': $!\n" ;
460 inflate $input => \$buffer
461 or die "inflate failed: $InflateError\n";
463 To uncompress all files in the directory "/my/home" that match "*.txt.1950" and store the compressed data in the same directory
467 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
469 inflate '</my/home/*.txt.1950>' => '</my/home/#1.txt>'
470 or die "inflate failed: $InflateError\n";
472 and if you want to compress each file one at a time, this will do the trick
476 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
478 for my $input ( glob "/my/home/*.txt.1950" )
481 $output =~ s/.1950// ;
482 inflate $input => $output
483 or die "Error compressing '$input': $InflateError\n";
490 The format of the constructor for IO::Uncompress::Inflate is shown below
492 my $z = new IO::Uncompress::Inflate $input [OPTS]
493 or die "IO::Uncompress::Inflate failed: $InflateError\n";
495 Returns an C<IO::Uncompress::Inflate> object on success and undef on failure.
496 The variable C<$InflateError> will contain an error message on failure.
498 If you are running Perl 5.005 or better the object, C<$z>, returned from
499 IO::Uncompress::Inflate can be used exactly like an L<IO::File|IO::File> filehandle.
500 This means that all normal input file operations can be carried out with
501 C<$z>. For example, to read a line from a compressed file/buffer you can
502 use either of these forms
504 $line = $z->getline();
507 The mandatory parameter C<$input> is used to determine the source of the
508 compressed data. This parameter can take one of three forms.
514 If the C<$input> parameter is a scalar, it is assumed to be a filename. This
515 file will be opened for reading and the compressed data will be read from it.
519 If the C<$input> parameter is a filehandle, the compressed data will be
521 The string '-' can be used as an alias for standard input.
523 =item A scalar reference
525 If C<$input> is a scalar reference, the compressed data will be read from
530 =head2 Constructor Options
532 The option names defined below are case insensitive and can be optionally
533 prefixed by a '-'. So all of the following are valid
540 OPTS is a combination of the following options:
544 =item C<< AutoClose => 0|1 >>
546 This option is only valid when the C<$input> parameter is a filehandle. If
547 specified, and the value is true, it will result in the file being closed once
548 either the C<close> method is called or the IO::Uncompress::Inflate object is
551 This parameter defaults to 0.
553 =item C<< MultiStream => 0|1 >>
555 Allows multiple concatenated compressed streams to be treated as a single
556 compressed stream. Decompression will stop once either the end of the
557 file/buffer is reached, an error is encountered (premature eof, corrupt
558 compressed data) or the end of a stream is not immediately followed by the
559 start of another stream.
561 This parameter defaults to 0.
563 =item C<< Prime => $string >>
565 This option will uncompress the contents of C<$string> before processing the
568 This option can be useful when the compressed data is embedded in another
569 file/data structure and it is not possible to work out where the compressed
570 data begins without having to read the first few bytes. If this is the
571 case, the uncompression can be I<primed> with these bytes using this
574 =item C<< Transparent => 0|1 >>
576 If this option is set and the input file/buffer is not compressed data,
577 the module will allow reading of it anyway.
579 In addition, if the input file/buffer does contain compressed data and
580 there is non-compressed data immediately following it, setting this option
581 will make this module treat the whole file/bufffer as a single data stream.
583 This option defaults to 1.
585 =item C<< BlockSize => $num >>
587 When reading the compressed input data, IO::Uncompress::Inflate will read it in
588 blocks of C<$num> bytes.
590 This option defaults to 4096.
592 =item C<< InputLength => $size >>
594 When present this option will limit the number of compressed bytes read
595 from the input file/buffer to C<$size>. This option can be used in the
596 situation where there is useful data directly after the compressed data
597 stream and you know beforehand the exact length of the compressed data
600 This option is mostly used when reading from a filehandle, in which case
601 the file pointer will be left pointing to the first byte directly after the
602 compressed data stream.
604 This option defaults to off.
606 =item C<< Append => 0|1 >>
608 This option controls what the C<read> method does with uncompressed data.
610 If set to 1, all uncompressed data will be appended to the output parameter
611 of the C<read> method.
613 If set to 0, the contents of the output parameter of the C<read> method
614 will be overwritten by the uncompressed data.
618 =item C<< Strict => 0|1 >>
620 This option controls whether the extra checks defined below are used when
621 carrying out the decompression. When Strict is on, the extra tests are
622 carried out, when Strict is off they are not.
624 The default for this option is off.
630 The ADLER32 checksum field must be present.
634 The value of the ADLER32 field read must match the adler32 value of the
635 uncompressed data actually contained in the file.
651 $status = $z->read($buffer)
653 Reads a block of compressed data (the size the the compressed block is
654 determined by the C<Buffer> option in the constructor), uncompresses it and
655 writes any uncompressed data into C<$buffer>. If the C<Append> parameter is
656 set in the constructor, the uncompressed data will be appended to the
657 C<$buffer> parameter. Otherwise C<$buffer> will be overwritten.
659 Returns the number of uncompressed bytes written to C<$buffer>, zero if eof
660 or a negative number on error.
666 $status = $z->read($buffer, $length)
667 $status = $z->read($buffer, $length, $offset)
669 $status = read($z, $buffer, $length)
670 $status = read($z, $buffer, $length, $offset)
672 Attempt to read C<$length> bytes of uncompressed data into C<$buffer>.
674 The main difference between this form of the C<read> method and the
675 previous one, is that this one will attempt to return I<exactly> C<$length>
676 bytes. The only circumstances that this function will not is if end-of-file
677 or an IO error is encountered.
679 Returns the number of uncompressed bytes written to C<$buffer>, zero if eof
680 or a negative number on error.
686 $line = $z->getline()
691 This method fully supports the use of of the variable C<$/> (or
692 C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
693 determine what constitutes an end of line. Paragraph mode, record mode and
694 file slurp mode are all supported.
702 Read a single character.
708 $char = $z->ungetc($string)
714 $status = $z->inflateSync()
722 $hdr = $z->getHeaderInfo();
723 @hdrs = $z->getHeaderInfo();
725 This method returns either a hash reference (in scalar context) or a list
726 or hash references (in array context) that contains information about each
727 of the header fields in the compressed data stream(s).
736 Returns the uncompressed file offset.
745 Returns true if the end of the compressed input stream has been reached.
749 $z->seek($position, $whence);
750 seek($z, $position, $whence);
752 Provides a sub-set of the C<seek> functionality, with the restriction
753 that it is only legal to seek forward in the input file/buffer.
754 It is a fatal error to attempt to seek backward.
756 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
757 SEEK_CUR or SEEK_END.
759 Returns 1 on success, 0 on failure.
768 This is a noop provided for completeness.
774 Returns true if the object currently refers to a opened file/buffer.
778 my $prev = $z->autoflush()
779 my $prev = $z->autoflush(EXPR)
781 If the C<$z> object is associated with a file or a filehandle, this method
782 returns the current autoflush setting for the underlying filehandle. If
783 C<EXPR> is present, and is non-zero, it will enable flushing after every
784 write/print operation.
786 If C<$z> is associated with a buffer, this method has no effect and always
789 B<Note> that the special variable C<$|> B<cannot> be used to set or
790 retrieve the autoflush setting.
792 =head2 input_line_number
794 $z->input_line_number()
795 $z->input_line_number(EXPR)
797 Returns the current uncompressed line number. If C<EXPR> is present it has
798 the effect of setting the line number. Note that setting the line number
799 does not change the current position within the file/buffer being read.
801 The contents of C<$/> are used to to determine what constitutes a line
809 If the C<$z> object is associated with a file or a filehandle, C<fileno>
810 will return the underlying file descriptor. Once the C<close> method is
811 called C<fileno> will return C<undef>.
813 If the C<$z> object is is associated with a buffer, this method will return
821 Closes the output file/buffer.
823 For most versions of Perl this method will be automatically invoked if
824 the IO::Uncompress::Inflate object is destroyed (either explicitly or by the
825 variable with the reference to the object going out of scope). The
826 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
827 these cases, the C<close> method will be called automatically, but
828 not until global destruction of all live objects when the program is
831 Therefore, if you want your scripts to be able to run on all versions
832 of Perl, you should call C<close> explicitly and not rely on automatic
835 Returns true on success, otherwise 0.
837 If the C<AutoClose> option has been enabled when the IO::Uncompress::Inflate
838 object was created, and the object is associated with a file, the
839 underlying file will also be closed.
845 my $status = $z->nextStream();
847 Skips to the next compressed data stream in the input file/buffer. If a new
848 compressed data stream is found, the eof marker will be cleared and C<$.>
851 Returns 1 if a new stream was found, 0 if none was found, and -1 if an
852 error was encountered.
858 my $data = $z->trailingData();
860 Returns the data, if any, that is present immediately after the compressed
861 data stream once uncompression is complete. It only makes sense to call
862 this method once the end of the compressed data stream has been
865 This option can be used when there is useful information immediately
866 following the compressed data stream, and you don't know the length of the
867 compressed data stream.
869 If the input is a buffer, C<trailingData> will return everything from the
870 end of the compressed data stream to the end of the buffer.
872 If the input is a filehandle, C<trailingData> will return the data that is
873 left in the filehandle input buffer once the end of the compressed data
874 stream has been reached. You can then use the filehandle to read the rest
877 Don't bother using C<trailingData> if the input is a filename.
879 If you know the length of the compressed data stream before you start
880 uncompressing, you can avoid having to use C<trailingData> by setting the
881 C<InputLength> option in the constructor.
885 No symbolic constants are required by this IO::Uncompress::Inflate at present.
891 Imports C<inflate> and C<$InflateError>.
894 use IO::Uncompress::Inflate qw(inflate $InflateError) ;
900 =head2 Working with Net::FTP
902 See L<IO::Uncompress::Inflate::FAQ|IO::Uncompress::Inflate::FAQ/"Compressed files and Net::FTP">
906 L<Compress::Zlib>, L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Compress::RawDeflate>, L<IO::Uncompress::RawInflate>, L<IO::Compress::Bzip2>, L<IO::Uncompress::Bunzip2>, L<IO::Compress::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
908 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
910 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
911 L<Archive::Tar|Archive::Tar>,
914 For RFC 1950, 1951 and 1952 see
915 F<http://www.faqs.org/rfcs/rfc1950.html>,
916 F<http://www.faqs.org/rfcs/rfc1951.html> and
917 F<http://www.faqs.org/rfcs/rfc1952.html>
919 The I<zlib> compression library was written by Jean-loup Gailly
920 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
922 The primary site for the I<zlib> compression library is
923 F<http://www.zlib.org>.
925 The primary site for gzip is F<http://www.gzip.org>.
929 This module was written by Paul Marquess, F<pmqs@cpan.org>.
931 =head1 MODIFICATION HISTORY
933 See the Changes file.
935 =head1 COPYRIGHT AND LICENSE
937 Copyright (c) 2005-2008 Paul Marquess. All rights reserved.
939 This program is free software; you can redistribute it and/or
940 modify it under the same terms as Perl itself.