Add and remove files forgotten in change #27384
[p5sagit/p5-mst-13.2.git] / ext / Compress / IO / Zlib / lib / IO / Uncompress / Unzip.pm
1 package IO::Uncompress::Unzip;
2
3 require 5.004 ;
4
5 # for RFC1952
6
7 use strict ;
8 use warnings;
9 use bytes;
10
11 use IO::Uncompress::RawInflate ;
12 use IO::Compress::Base::Common qw(:Status createSelfTiedObject);
13 use IO::Uncompress::Adapter::Identity;
14
15 require Exporter ;
16
17 our ($VERSION, @ISA, @EXPORT_OK, %EXPORT_TAGS, $UnzipError);
18
19 $VERSION = '2.000_08';
20 $UnzipError = '';
21
22 @ISA    = qw(Exporter IO::Uncompress::RawInflate);
23 @EXPORT_OK = qw( $UnzipError unzip );
24 %EXPORT_TAGS = %IO::Uncompress::RawInflate::EXPORT_TAGS ;
25 push @{ $EXPORT_TAGS{all} }, @EXPORT_OK ;
26 Exporter::export_ok_tags('all');
27
28
29 sub new
30 {
31     my $class = shift ;
32     my $obj = createSelfTiedObject($class, \$UnzipError);
33     $obj->_create(undef, 0, @_);
34 }
35
36 sub unzip
37 {
38     my $obj = createSelfTiedObject(undef, \$UnzipError);
39     return $obj->_inf(@_) ;
40 }
41
42 sub getExtraParams
43 {
44     use IO::Compress::Base::Common qw(:Parse);
45
46     
47     return (
48 #            # Zip header fields
49             'Name'      => [1, 1, Parse_any,       undef],
50
51 #            'Streaming' => [1, 1, Parse_boolean,   1],
52         );    
53 }
54
55 sub ckParams
56 {
57     my $self = shift ;
58     my $got = shift ;
59
60     # unzip always needs crc32
61     $got->value('CRC32' => 1);
62
63     *$self->{UnzipData}{Name} = $got->value('Name');
64
65     return 1;
66 }
67
68
69 sub ckMagic
70 {
71     my $self = shift;
72
73     my $magic ;
74     $self->smartReadExact(\$magic, 4);
75
76     *$self->{HeaderPending} = $magic ;
77
78     return $self->HeaderError("Minimum header size is " . 
79                               4 . " bytes") 
80         if length $magic != 4 ;                                    
81
82     return $self->HeaderError("Bad Magic")
83         if ! _isZipMagic($magic) ;
84
85     *$self->{Type} = 'zip';
86
87     return $magic ;
88 }
89
90
91
92 sub readHeader
93 {
94     my $self = shift;
95     my $magic = shift ;
96
97     my $name =  *$self->{UnzipData}{Name} ;
98     my $hdr = $self->_readZipHeader($magic) ;
99
100     while (defined $hdr)
101     {
102         if (! defined $name || $hdr->{Name} eq $name)
103         {
104             return $hdr ;
105         }
106
107         # skip the data
108         my $buffer;
109         if (*$self->{ZipData}{Streaming}) {
110
111             while (1) {
112
113                 my $b;
114                 my $status = $self->smartRead(\$b, 1024 * 16);
115                 return undef
116                     if $status <= 0 ;
117
118                 my $temp_buf;
119                 my $out;
120                 $status = *$self->{Uncomp}->uncompr(\$b, \$temp_buf, 0, $out);
121
122                 return $self->saveErrorString(undef, *$self->{Uncomp}{Error}, 
123                                                      *$self->{Uncomp}{ErrorNo})
124                     if $self->saveStatus($status) == STATUS_ERROR;                
125
126                 if ($status == STATUS_ENDSTREAM) {
127                     *$self->{Uncomp}->reset();
128                     $self->pushBack($b)  ;
129                     last;
130                 }
131             }
132
133             # skip the trailer
134             $self->smartReadExact(\$buffer, $hdr->{TrailerLength})
135                 or return $self->saveErrorString(undef, "Truncated file");
136         }
137         else {
138             my $c = $hdr->{CompressedLength};
139             $self->smartReadExact(\$buffer, $c)
140                 or return $self->saveErrorString(undef, "Truncated file");
141             $buffer = '';
142         }
143
144         $self->chkTrailer($buffer) == STATUS_OK
145             or return $self->saveErrorString(undef, "Truncated file");
146
147         $hdr = $self->_readFullZipHeader();
148
149         return $self->saveErrorString(undef, "Cannot find '$name'")
150             if $self->smartEof();
151     }
152
153     return undef;
154 }
155
156 sub chkTrailer
157 {
158     my $self = shift;
159     my $trailer = shift;
160
161     my ($sig, $CRC32, $cSize, $uSize) ;
162     if (*$self->{ZipData}{Streaming}) {
163         ($sig, $CRC32, $cSize, $uSize) = unpack("V V V V", $trailer) ;
164         return $self->TrailerError("Data Descriptor signature, got $sig")
165             if $sig != 0x08074b50;
166     }
167     else {
168         ($CRC32, $cSize, $uSize) = 
169             (*$self->{ZipData}{Crc32},
170              *$self->{ZipData}{CompressedLen},
171              *$self->{ZipData}{UnCompressedLen});
172     }
173
174     if (*$self->{Strict}) {
175         #return $self->TrailerError("CRC mismatch")
176         #    if $CRC32  != *$self->{Uncomp}->crc32() ;
177
178         my $exp_isize = *$self->{Uncomp}->compressedBytes();
179         return $self->TrailerError("CSIZE mismatch. Got $cSize"
180                                   . ", expected $exp_isize")
181             if $cSize != $exp_isize ;
182
183         $exp_isize = *$self->{Uncomp}->uncompressedBytes();
184         return $self->TrailerError("USIZE mismatch. Got $uSize"
185                                   . ", expected $exp_isize")
186             if $uSize != $exp_isize ;
187     }
188
189     my $reachedEnd = STATUS_ERROR ;
190     # check for central directory or end of central directory
191     while (1)
192     {
193         my $magic ;
194         my $got = $self->smartRead(\$magic, 4);
195
196         return $self->saveErrorString(STATUS_ERROR, "Truncated file")
197             if $got != 4 && *$self->{Strict};
198
199         if ($got == 0) {
200             return STATUS_EOF ;
201         }
202         elsif ($got < 0) {
203             return STATUS_ERROR ;
204         }
205         elsif ($got < 4) {
206             $self->pushBack($magic)  ;
207             return STATUS_OK ;
208         }
209
210         my $sig = unpack("V", $magic) ;
211
212         if ($sig == 0x02014b50)
213         {
214             if ($self->skipCentralDirectory($magic) != STATUS_OK ) {
215                 if (*$self->{Strict}) {
216                     return STATUS_ERROR ;
217                 }
218                 else {
219                     $self->clearError();
220                     return STATUS_OK ;
221                 }
222             }
223         }
224         elsif ($sig == 0x06054b50)
225         {
226             if ($self->skipEndCentralDirectory($magic) != STATUS_OK) {
227                 if (*$self->{Strict}) {
228                     return STATUS_ERROR ;
229                 }
230                 else {
231                     $self->clearError();
232                     return STATUS_OK ;
233                 }
234             }
235             # $reachedEnd = STATUS_OK ;
236             return STATUS_OK ;
237             last;
238         }
239         elsif ($sig == 0x04034b50)
240         {
241             $self->pushBack($magic)  ;
242             return STATUS_OK ;
243         }
244         else
245         {
246             # put the data back
247             $self->pushBack($magic)  ;
248             last;
249         }
250     }
251
252     return $reachedEnd ;
253 }
254
255 sub skipCentralDirectory
256 {
257     my $self = shift;
258     my $magic = shift ;
259
260     my $buffer;
261     $self->smartReadExact(\$buffer, 46 - 4)
262         or return $self->TrailerError("Minimum header size is " . 
263                                      46 . " bytes") ;
264
265     my $keep = $magic . $buffer ;
266     *$self->{HeaderPending} = $keep ;
267
268    #my $versionMadeBy      = unpack ("v", substr($buffer, 4-4,  2));
269    #my $extractVersion     = unpack ("v", substr($buffer, 6-4,  2));
270    #my $gpFlag             = unpack ("v", substr($buffer, 8-4,  2));
271    #my $compressedMethod   = unpack ("v", substr($buffer, 10-4, 2));
272    #my $lastModTime        = unpack ("V", substr($buffer, 12-4, 4));
273    #my $crc32              = unpack ("V", substr($buffer, 16-4, 4));
274    #my $compressedLength   = unpack ("V", substr($buffer, 20-4, 4));
275    #my $uncompressedLength = unpack ("V", substr($buffer, 24-4, 4));
276     my $filename_length    = unpack ("v", substr($buffer, 28-4, 2)); 
277     my $extra_length       = unpack ("v", substr($buffer, 30-4, 2));
278     my $comment_length     = unpack ("v", substr($buffer, 32-4, 2));
279    #my $disk_start         = unpack ("v", substr($buffer, 34-4, 2));
280    #my $int_file_attrib    = unpack ("v", substr($buffer, 36-4, 2));
281    #my $ext_file_attrib    = unpack ("V", substr($buffer, 38-4, 2));
282    #my $lcl_hdr_offset     = unpack ("V", substr($buffer, 42-4, 2));
283
284     
285     my $filename;
286     my $extraField;
287     my $comment ;
288     if ($filename_length)
289     {
290         $self->smartReadExact(\$filename, $filename_length)
291             or return $self->TrailerError("xxx");
292         $keep .= $filename ;
293     }
294
295     if ($extra_length)
296     {
297         $self->smartReadExact(\$extraField, $extra_length)
298             or return $self->TrailerError("xxx");
299         $keep .= $extraField ;
300     }
301
302     if ($comment_length)
303     {
304         $self->smartReadExact(\$comment, $comment_length)
305             or return $self->TrailerError("xxx");
306         $keep .= $comment ;
307     }
308
309     return STATUS_OK ;
310 }
311
312 sub skipEndCentralDirectory
313 {
314     my $self = shift;
315     my $magic = shift ;
316
317     my $buffer;
318     $self->smartReadExact(\$buffer, 22 - 4)
319         or return $self->TrailerError("Minimum header size is " . 
320                                      22 . " bytes") ;
321
322     my $keep = $magic . $buffer ;
323     *$self->{HeaderPending} = $keep ;
324
325    #my $diskNumber         = unpack ("v", substr($buffer, 4-4,  2));
326    #my $cntrlDirDiskNo     = unpack ("v", substr($buffer, 6-4,  2));
327    #my $entriesInThisCD    = unpack ("v", substr($buffer, 8-4,  2));
328    #my $entriesInCD        = unpack ("v", substr($buffer, 10-4, 2));
329    #my $sizeOfCD           = unpack ("V", substr($buffer, 12-4, 2));
330    #my $offsetToCD         = unpack ("V", substr($buffer, 16-4, 2));
331     my $comment_length     = unpack ("v", substr($buffer, 20-4, 2));
332
333     
334     my $comment ;
335     if ($comment_length)
336     {
337         $self->smartReadExact(\$comment, $comment_length)
338             or return $self->TrailerError("xxx");
339         $keep .= $comment ;
340     }
341
342     return STATUS_OK ;
343 }
344
345
346
347
348 sub _isZipMagic
349 {
350     my $buffer = shift ;
351     return 0 if length $buffer < 4 ;
352     my $sig = unpack("V", $buffer) ;
353     return $sig == 0x04034b50 ;
354 }
355
356
357 sub _readFullZipHeader($)
358 {
359     my ($self) = @_ ;
360     my $magic = '' ;
361
362     $self->smartReadExact(\$magic, 4);
363
364     *$self->{HeaderPending} = $magic ;
365
366     return $self->HeaderError("Minimum header size is " . 
367                               30 . " bytes") 
368         if length $magic != 4 ;                                    
369
370
371     return $self->HeaderError("Bad Magic")
372         if ! _isZipMagic($magic) ;
373
374     my $status = $self->_readZipHeader($magic);
375     delete *$self->{Transparent} if ! defined $status ;
376     return $status ;
377 }
378
379 sub _readZipHeader($)
380 {
381     my ($self, $magic) = @_ ;
382     my ($HeaderCRC) ;
383     my ($buffer) = '' ;
384
385     $self->smartReadExact(\$buffer, 30 - 4)
386         or return $self->HeaderError("Minimum header size is " . 
387                                      30 . " bytes") ;
388
389     my $keep = $magic . $buffer ;
390     *$self->{HeaderPending} = $keep ;
391
392     my $extractVersion     = unpack ("v", substr($buffer, 4-4,  2));
393     my $gpFlag             = unpack ("v", substr($buffer, 6-4,  2));
394     my $compressedMethod   = unpack ("v", substr($buffer, 8-4,  2));
395     my $lastModTime        = unpack ("V", substr($buffer, 10-4, 4));
396     my $crc32              = unpack ("V", substr($buffer, 14-4, 4));
397     my $compressedLength   = unpack ("V", substr($buffer, 18-4, 4));
398     my $uncompressedLength = unpack ("V", substr($buffer, 22-4, 4));
399     my $filename_length    = unpack ("v", substr($buffer, 26-4, 2)); 
400     my $extra_length       = unpack ("v", substr($buffer, 28-4, 2));
401
402     my $filename;
403     my $extraField;
404     my $streamingMode = ($gpFlag & 0x08) ? 1 : 0 ;
405
406     return $self->HeaderError("Streamed Stored content not supported")
407         if $streamingMode && $compressedMethod == 0 ;
408
409     *$self->{ZipData}{Streaming} = $streamingMode;
410
411     if (! $streamingMode) {
412         *$self->{ZipData}{Streaming} = 0;
413         *$self->{ZipData}{Crc32} = $crc32;
414         *$self->{ZipData}{CompressedLen} = $compressedLength;
415         *$self->{ZipData}{UnCompressedLen} = $uncompressedLength;
416         *$self->{CompressedInputLengthRemaining} =
417             *$self->{CompressedInputLength} = $compressedLength;
418     }
419
420
421     if ($filename_length)
422     {
423         $self->smartReadExact(\$filename, $filename_length)
424             or return $self->HeaderError("xxx");
425         $keep .= $filename ;
426     }
427
428     if ($extra_length)
429     {
430         $self->smartReadExact(\$extraField, $extra_length)
431             or return $self->HeaderError("xxx");
432         $keep .= $extraField ;
433     }
434
435     if ($compressedMethod == 8)
436     {
437         *$self->{Type} = 'zip';
438     }
439     elsif ($compressedMethod == 0)
440     {
441         # TODO -- add support for reading uncompressed
442
443         *$self->{Type} = 'zipStored';
444         
445         my $obj = IO::Uncompress::Adapter::Identity::mkUncompObject(# $got->value('CRC32'),
446                                                              # $got->value('ADLER32'),
447                                                               );
448
449         *$self->{Uncomp} = $obj;
450
451     }
452     else
453     {
454         return $self->HeaderError("Unsupported Compression format $compressedMethod");
455     }
456
457     return {
458         'Type'               => 'zip',
459         'FingerprintLength'  => 4,
460         #'HeaderLength'       => $compressedMethod == 8 ? length $keep : 0,
461         'HeaderLength'       => length $keep,
462         'TrailerLength'      => $streamingMode ? 16  : 0,
463         'Header'             => $keep,
464         'CompressedLength'   => $compressedLength ,
465         'UncompressedLength' => $uncompressedLength ,
466         'CRC32'              => $crc32 ,
467         'Name'               => $filename,
468         'Time'               => _dosToUnixTime($lastModTime),
469         'Stream'             => $streamingMode,
470
471         'MethodID'           => $compressedMethod,
472         'MethodName'         => $compressedMethod == 8 
473                                  ? "Deflated" 
474                                  : $compressedMethod == 0
475                                      ? "Stored"
476                                      : "Unknown" ,
477
478 #        'TextFlag'      => $flag & GZIP_FLG_FTEXT ? 1 : 0,
479 #        'HeaderCRCFlag' => $flag & GZIP_FLG_FHCRC ? 1 : 0,
480 #        'NameFlag'      => $flag & GZIP_FLG_FNAME ? 1 : 0,
481 #        'CommentFlag'   => $flag & GZIP_FLG_FCOMMENT ? 1 : 0,
482 #        'ExtraFlag'     => $flag & GZIP_FLG_FEXTRA ? 1 : 0,
483 #        'Comment'       => $comment,
484 #        'OsID'          => $os,
485 #        'OsName'        => defined $GZIP_OS_Names{$os} 
486 #                                 ? $GZIP_OS_Names{$os} : "Unknown",
487 #        'HeaderCRC'     => $HeaderCRC,
488 #        'Flags'         => $flag,
489 #        'ExtraFlags'    => $xfl,
490 #        'ExtraFieldRaw' => $EXTRA,
491 #        'ExtraField'    => [ @EXTRA ],
492
493
494       }
495 }
496
497 # from Archive::Zip
498 sub _dosToUnixTime
499 {
500     #use Time::Local 'timelocal_nocheck';
501     use Time::Local 'timelocal';
502
503         my $dt = shift;
504
505         my $year = ( ( $dt >> 25 ) & 0x7f ) + 80;
506         my $mon  = ( ( $dt >> 21 ) & 0x0f ) - 1;
507         my $mday = ( ( $dt >> 16 ) & 0x1f );
508
509         my $hour = ( ( $dt >> 11 ) & 0x1f );
510         my $min  = ( ( $dt >> 5 ) & 0x3f );
511         my $sec  = ( ( $dt << 1 ) & 0x3e );
512
513         # catch errors
514         my $time_t =
515           eval { timelocal( $sec, $min, $hour, $mday, $mon, $year ); };
516         return 0 
517         if $@;
518         return $time_t;
519 }
520
521
522 1;
523
524 __END__
525
526
527 =head1 NAME
528
529
530 IO::Uncompress::Unzip - Perl interface to read zip files/buffers
531
532
533 =head1 SYNOPSIS
534
535     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
536
537     my $status = unzip $input => $output [,OPTS]
538         or die "unzip failed: $UnzipError\n";
539
540     my $z = new IO::Uncompress::Unzip $input [OPTS] 
541         or die "unzip failed: $UnzipError\n";
542
543     $status = $z->read($buffer)
544     $status = $z->read($buffer, $length)
545     $status = $z->read($buffer, $length, $offset)
546     $line = $z->getline()
547     $char = $z->getc()
548     $char = $z->ungetc()
549     $char = $z->opened()
550
551     $status = $z->inflateSync()
552
553     $z->trailingData()
554     $data = $z->getHeaderInfo()
555     $z->tell()
556     $z->seek($position, $whence)
557     $z->binmode()
558     $z->fileno()
559     $z->eof()
560     $z->close()
561
562     $UnzipError ;
563
564     # IO::File mode
565
566     <$z>
567     read($z, $buffer);
568     read($z, $buffer, $length);
569     read($z, $buffer, $length, $offset);
570     tell($z)
571     seek($z, $position, $whence)
572     binmode($z)
573     fileno($z)
574     eof($z)
575     close($z)
576
577
578 =head1 DESCRIPTION
579
580
581
582 B<WARNING -- This is a Beta release>. 
583
584 =over 5
585
586 =item * DO NOT use in production code.
587
588 =item * The documentation is incomplete in places.
589
590 =item * Parts of the interface defined here are tentative.
591
592 =item * Please report any problems you find.
593
594 =back
595
596
597
598
599
600 This module provides a Perl interface that allows the reading of
601 zlib files/buffers.
602
603 For writing zip files/buffers, see the companion module IO::Compress::Zip.
604
605
606
607 =head1 Functional Interface
608
609 A top-level function, C<unzip>, is provided to carry out
610 "one-shot" uncompression between buffers and/or files. For finer
611 control over the uncompression process, see the L</"OO Interface">
612 section.
613
614     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
615
616     unzip $input => $output [,OPTS] 
617         or die "unzip failed: $UnzipError\n";
618
619
620
621 The functional interface needs Perl5.005 or better.
622
623
624 =head2 unzip $input => $output [, OPTS]
625
626
627 C<unzip> expects at least two parameters, C<$input> and C<$output>.
628
629 =head3 The C<$input> parameter
630
631 The parameter, C<$input>, is used to define the source of
632 the compressed data. 
633
634 It can take one of the following forms:
635
636 =over 5
637
638 =item A filename
639
640 If the C<$input> parameter is a simple scalar, it is assumed to be a
641 filename. This file will be opened for reading and the input data
642 will be read from it.
643
644 =item A filehandle
645
646 If the C<$input> parameter is a filehandle, the input data will be
647 read from it.
648 The string '-' can be used as an alias for standard input.
649
650 =item A scalar reference 
651
652 If C<$input> is a scalar reference, the input data will be read
653 from C<$$input>.
654
655 =item An array reference 
656
657 If C<$input> is an array reference, each element in the array must be a
658 filename.
659
660 The input data will be read from each file in turn. 
661
662 The complete array will be walked to ensure that it only
663 contains valid filenames before any data is uncompressed.
664
665
666
667 =item An Input FileGlob string
668
669 If C<$input> is a string that is delimited by the characters "<" and ">"
670 C<unzip> will assume that it is an I<input fileglob string>. The
671 input is the list of files that match the fileglob.
672
673 If the fileglob does not match any files ...
674
675 See L<File::GlobMapper|File::GlobMapper> for more details.
676
677
678 =back
679
680 If the C<$input> parameter is any other type, C<undef> will be returned.
681
682
683
684 =head3 The C<$output> parameter
685
686 The parameter C<$output> is used to control the destination of the
687 uncompressed data. This parameter can take one of these forms.
688
689 =over 5
690
691 =item A filename
692
693 If the C<$output> parameter is a simple scalar, it is assumed to be a
694 filename.  This file will be opened for writing and the uncompressed
695 data will be written to it.
696
697 =item A filehandle
698
699 If the C<$output> parameter is a filehandle, the uncompressed data
700 will be written to it.
701 The string '-' can be used as an alias for standard output.
702
703
704 =item A scalar reference 
705
706 If C<$output> is a scalar reference, the uncompressed data will be
707 stored in C<$$output>.
708
709
710
711 =item An Array Reference
712
713 If C<$output> is an array reference, the uncompressed data will be
714 pushed onto the array.
715
716 =item An Output FileGlob
717
718 If C<$output> is a string that is delimited by the characters "<" and ">"
719 C<unzip> will assume that it is an I<output fileglob string>. The
720 output is the list of files that match the fileglob.
721
722 When C<$output> is an fileglob string, C<$input> must also be a fileglob
723 string. Anything else is an error.
724
725 =back
726
727 If the C<$output> parameter is any other type, C<undef> will be returned.
728
729
730
731 =head2 Notes
732
733 When C<$input> maps to multiple files/buffers and C<$output> is a single
734 file/buffer the uncompressed input files/buffers will all be stored
735 in C<$output> as a single uncompressed stream.
736
737
738
739 =head2 Optional Parameters
740
741 Unless specified below, the optional parameters for C<unzip>,
742 C<OPTS>, are the same as those used with the OO interface defined in the
743 L</"Constructor Options"> section below.
744
745 =over 5
746
747 =item AutoClose =E<gt> 0|1
748
749 This option applies to any input or output data streams to 
750 C<unzip> that are filehandles.
751
752 If C<AutoClose> is specified, and the value is true, it will result in all
753 input and/or output filehandles being closed once C<unzip> has
754 completed.
755
756 This parameter defaults to 0.
757
758
759
760 =item BinModeOut =E<gt> 0|1
761
762 When writing to a file or filehandle, set C<binmode> before writing to the
763 file.
764
765 Defaults to 0.
766
767
768
769
770
771 =item -Append =E<gt> 0|1
772
773 TODO
774
775 =item -MultiStream =E<gt> 0|1
776
777 Creates a new stream after each file.
778
779 Defaults to 1.
780
781
782
783 =back
784
785
786
787
788 =head2 Examples
789
790 To read the contents of the file C<file1.txt.zip> and write the
791 compressed data to the file C<file1.txt>.
792
793     use strict ;
794     use warnings ;
795     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
796
797     my $input = "file1.txt.zip";
798     my $output = "file1.txt";
799     unzip $input => $output
800         or die "unzip failed: $UnzipError\n";
801
802
803 To read from an existing Perl filehandle, C<$input>, and write the
804 uncompressed data to a buffer, C<$buffer>.
805
806     use strict ;
807     use warnings ;
808     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
809     use IO::File ;
810
811     my $input = new IO::File "<file1.txt.zip"
812         or die "Cannot open 'file1.txt.zip': $!\n" ;
813     my $buffer ;
814     unzip $input => \$buffer 
815         or die "unzip failed: $UnzipError\n";
816
817 To uncompress all files in the directory "/my/home" that match "*.txt.zip" and store the compressed data in the same directory
818
819     use strict ;
820     use warnings ;
821     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
822
823     unzip '</my/home/*.txt.zip>' => '</my/home/#1.txt>'
824         or die "unzip failed: $UnzipError\n";
825
826 and if you want to compress each file one at a time, this will do the trick
827
828     use strict ;
829     use warnings ;
830     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
831
832     for my $input ( glob "/my/home/*.txt.zip" )
833     {
834         my $output = $input;
835         $output =~ s/.zip// ;
836         unzip $input => $output 
837             or die "Error compressing '$input': $UnzipError\n";
838     }
839
840 =head1 OO Interface
841
842 =head2 Constructor
843
844 The format of the constructor for IO::Uncompress::Unzip is shown below
845
846
847     my $z = new IO::Uncompress::Unzip $input [OPTS]
848         or die "IO::Uncompress::Unzip failed: $UnzipError\n";
849
850 Returns an C<IO::Uncompress::Unzip> object on success and undef on failure.
851 The variable C<$UnzipError> will contain an error message on failure.
852
853 If you are running Perl 5.005 or better the object, C<$z>, returned from
854 IO::Uncompress::Unzip can be used exactly like an L<IO::File|IO::File> filehandle.
855 This means that all normal input file operations can be carried out with
856 C<$z>.  For example, to read a line from a compressed file/buffer you can
857 use either of these forms
858
859     $line = $z->getline();
860     $line = <$z>;
861
862 The mandatory parameter C<$input> is used to determine the source of the
863 compressed data. This parameter can take one of three forms.
864
865 =over 5
866
867 =item A filename
868
869 If the C<$input> parameter is a scalar, it is assumed to be a filename. This
870 file will be opened for reading and the compressed data will be read from it.
871
872 =item A filehandle
873
874 If the C<$input> parameter is a filehandle, the compressed data will be
875 read from it.
876 The string '-' can be used as an alias for standard input.
877
878
879 =item A scalar reference 
880
881 If C<$input> is a scalar reference, the compressed data will be read from
882 C<$$output>.
883
884 =back
885
886 =head2 Constructor Options
887
888
889 The option names defined below are case insensitive and can be optionally
890 prefixed by a '-'.  So all of the following are valid
891
892     -AutoClose
893     -autoclose
894     AUTOCLOSE
895     autoclose
896
897 OPTS is a combination of the following options:
898
899 =over 5
900
901 =item -AutoClose =E<gt> 0|1
902
903 This option is only valid when the C<$input> parameter is a filehandle. If
904 specified, and the value is true, it will result in the file being closed once
905 either the C<close> method is called or the IO::Uncompress::Unzip object is
906 destroyed.
907
908 This parameter defaults to 0.
909
910 =item -MultiStream =E<gt> 0|1
911
912
913
914 Allows multiple concatenated compressed streams to be treated as a single
915 compressed stream. Decompression will stop once either the end of the
916 file/buffer is reached, an error is encountered (premature eof, corrupt
917 compressed data) or the end of a stream is not immediately followed by the
918 start of another stream.
919
920 This parameter defaults to 0.
921
922
923
924 =item -Prime =E<gt> $string
925
926 This option will uncompress the contents of C<$string> before processing the
927 input file/buffer.
928
929 This option can be useful when the compressed data is embedded in another
930 file/data structure and it is not possible to work out where the compressed
931 data begins without having to read the first few bytes. If this is the
932 case, the uncompression can be I<primed> with these bytes using this
933 option.
934
935 =item -Transparent =E<gt> 0|1
936
937 If this option is set and the input file or buffer is not compressed data,
938 the module will allow reading of it anyway.
939
940 This option defaults to 1.
941
942 =item -BlockSize =E<gt> $num
943
944 When reading the compressed input data, IO::Uncompress::Unzip will read it in
945 blocks of C<$num> bytes.
946
947 This option defaults to 4096.
948
949 =item -InputLength =E<gt> $size
950
951 When present this option will limit the number of compressed bytes read
952 from the input file/buffer to C<$size>. This option can be used in the
953 situation where there is useful data directly after the compressed data
954 stream and you know beforehand the exact length of the compressed data
955 stream. 
956
957 This option is mostly used when reading from a filehandle, in which case
958 the file pointer will be left pointing to the first byte directly after the
959 compressed data stream.
960
961
962
963 This option defaults to off.
964
965 =item -Append =E<gt> 0|1
966
967 This option controls what the C<read> method does with uncompressed data.
968
969 If set to 1, all uncompressed data will be appended to the output parameter
970 of the C<read> method.
971
972 If set to 0, the contents of the output parameter of the C<read> method
973 will be overwritten by the uncompressed data.
974
975 Defaults to 0.
976
977 =item -Strict =E<gt> 0|1
978
979
980
981 This option controls whether the extra checks defined below are used when
982 carrying out the decompression. When Strict is on, the extra tests are
983 carried out, when Strict is off they are not.
984
985 The default for this option is off.
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000 =back
1001
1002 =head2 Examples
1003
1004 TODO
1005
1006 =head1 Methods 
1007
1008 =head2 read
1009
1010 Usage is
1011
1012     $status = $z->read($buffer)
1013
1014 Reads a block of compressed data (the size the the compressed block is
1015 determined by the C<Buffer> option in the constructor), uncompresses it and
1016 writes any uncompressed data into C<$buffer>. If the C<Append> parameter is
1017 set in the constructor, the uncompressed data will be appended to the
1018 C<$buffer> parameter. Otherwise C<$buffer> will be overwritten.
1019
1020 Returns the number of uncompressed bytes written to C<$buffer>, zero if eof
1021 or a negative number on error.
1022
1023 =head2 read
1024
1025 Usage is
1026
1027     $status = $z->read($buffer, $length)
1028     $status = $z->read($buffer, $length, $offset)
1029
1030     $status = read($z, $buffer, $length)
1031     $status = read($z, $buffer, $length, $offset)
1032
1033 Attempt to read C<$length> bytes of uncompressed data into C<$buffer>.
1034
1035 The main difference between this form of the C<read> method and the
1036 previous one, is that this one will attempt to return I<exactly> C<$length>
1037 bytes. The only circumstances that this function will not is if end-of-file
1038 or an IO error is encountered.
1039
1040 Returns the number of uncompressed bytes written to C<$buffer>, zero if eof
1041 or a negative number on error.
1042
1043
1044 =head2 getline
1045
1046 Usage is
1047
1048     $line = $z->getline()
1049     $line = <$z>
1050
1051 Reads a single line. 
1052
1053 This method fully supports the use of of the variable C<$/>
1054 (or C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
1055 determine what constitutes an end of line. Both paragraph mode and file
1056 slurp mode are supported. 
1057
1058
1059 =head2 getc
1060
1061 Usage is 
1062
1063     $char = $z->getc()
1064
1065 Read a single character.
1066
1067 =head2 ungetc
1068
1069 Usage is
1070
1071     $char = $z->ungetc($string)
1072
1073
1074
1075 =head2 inflateSync
1076
1077 Usage is
1078
1079     $status = $z->inflateSync()
1080
1081 TODO
1082
1083
1084 =head2 getHeaderInfo
1085
1086 Usage is
1087
1088     $hdr  = $z->getHeaderInfo();
1089     @hdrs = $z->getHeaderInfo();
1090
1091 This method returns either a hash reference (in scalar context) or a list
1092 or hash references (in array context) that contains information about each
1093 of the header fields in the compressed data stream(s).
1094
1095
1096
1097
1098 =head2 tell
1099
1100 Usage is
1101
1102     $z->tell()
1103     tell $z
1104
1105 Returns the uncompressed file offset.
1106
1107 =head2 eof
1108
1109 Usage is
1110
1111     $z->eof();
1112     eof($z);
1113
1114
1115
1116 Returns true if the end of the compressed input stream has been reached.
1117
1118
1119
1120 =head2 seek
1121
1122     $z->seek($position, $whence);
1123     seek($z, $position, $whence);
1124
1125
1126
1127
1128 Provides a sub-set of the C<seek> functionality, with the restriction
1129 that it is only legal to seek forward in the input file/buffer.
1130 It is a fatal error to attempt to seek backward.
1131
1132
1133
1134 The C<$whence> parameter takes one the usual values, namely SEEK_SET,
1135 SEEK_CUR or SEEK_END.
1136
1137 Returns 1 on success, 0 on failure.
1138
1139 =head2 binmode
1140
1141 Usage is
1142
1143     $z->binmode
1144     binmode $z ;
1145
1146 This is a noop provided for completeness.
1147
1148 =head2 opened
1149
1150     $z->opened()
1151
1152 Returns true if the object currently refers to a opened file/buffer. 
1153
1154 =head2 autoflush
1155
1156     my $prev = $z->autoflush()
1157     my $prev = $z->autoflush(EXPR)
1158
1159 If the C<$z> object is associated with a file or a filehandle, this method
1160 returns the current autoflush setting for the underlying filehandle. If
1161 C<EXPR> is present, and is non-zero, it will enable flushing after every
1162 write/print operation.
1163
1164 If C<$z> is associated with a buffer, this method has no effect and always
1165 returns C<undef>.
1166
1167 B<Note> that the special variable C<$|> B<cannot> be used to set or
1168 retrieve the autoflush setting.
1169
1170 =head2 input_line_number
1171
1172     $z->input_line_number()
1173     $z->input_line_number(EXPR)
1174
1175
1176
1177 Returns the current uncompressed line number. If C<EXPR> is present it has
1178 the effect of setting the line number. Note that setting the line number
1179 does not change the current position within the file/buffer being read.
1180
1181 The contents of C<$/> are used to to determine what constitutes a line
1182 terminator.
1183
1184
1185
1186 =head2 fileno
1187
1188     $z->fileno()
1189     fileno($z)
1190
1191 If the C<$z> object is associated with a file or a filehandle, this method
1192 will return the underlying file descriptor.
1193
1194 If the C<$z> object is is associated with a buffer, this method will
1195 return undef.
1196
1197 =head2 close
1198
1199     $z->close() ;
1200     close $z ;
1201
1202
1203
1204 Closes the output file/buffer. 
1205
1206
1207
1208 For most versions of Perl this method will be automatically invoked if
1209 the IO::Uncompress::Unzip object is destroyed (either explicitly or by the
1210 variable with the reference to the object going out of scope). The
1211 exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In
1212 these cases, the C<close> method will be called automatically, but
1213 not until global destruction of all live objects when the program is
1214 terminating.
1215
1216 Therefore, if you want your scripts to be able to run on all versions
1217 of Perl, you should call C<close> explicitly and not rely on automatic
1218 closing.
1219
1220 Returns true on success, otherwise 0.
1221
1222 If the C<AutoClose> option has been enabled when the IO::Uncompress::Unzip
1223 object was created, and the object is associated with a file, the
1224 underlying file will also be closed.
1225
1226
1227
1228
1229 =head1 Importing 
1230
1231 No symbolic constants are required by this IO::Uncompress::Unzip at present. 
1232
1233 =over 5
1234
1235 =item :all
1236
1237 Imports C<unzip> and C<$UnzipError>.
1238 Same as doing this
1239
1240     use IO::Uncompress::Unzip qw(unzip $UnzipError) ;
1241
1242 =back
1243
1244 =head1 EXAMPLES
1245
1246
1247
1248
1249 =head1 SEE ALSO
1250
1251 L<Compress::Zlib>, L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, 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::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
1252
1253 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1254
1255 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1256 L<Archive::Tar|Archive::Tar>,
1257 L<IO::Zlib|IO::Zlib>
1258
1259
1260 For RFC 1950, 1951 and 1952 see 
1261 F<http://www.faqs.org/rfcs/rfc1950.html>,
1262 F<http://www.faqs.org/rfcs/rfc1951.html> and
1263 F<http://www.faqs.org/rfcs/rfc1952.html>
1264
1265 The I<zlib> compression library was written by Jean-loup Gailly
1266 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1267
1268 The primary site for the I<zlib> compression library is
1269 F<http://www.zlib.org>.
1270
1271 The primary site for gzip is F<http://www.gzip.org>.
1272
1273
1274
1275
1276
1277
1278
1279 =head1 AUTHOR
1280
1281 The I<IO::Uncompress::Unzip> module was written by Paul Marquess,
1282 F<pmqs@cpan.org>. 
1283
1284
1285
1286 =head1 MODIFICATION HISTORY
1287
1288 See the Changes file.
1289
1290 =head1 COPYRIGHT AND LICENSE
1291  
1292
1293 Copyright (c) 2005-2006 Paul Marquess. All rights reserved.
1294
1295 This program is free software; you can redistribute it and/or
1296 modify it under the same terms as Perl itself.
1297