/
zip.rb
executable file
·1880 lines (1626 loc) · 51.9 KB
/
zip.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'delegate'
require 'iconv'
require 'singleton'
require 'tempfile'
require 'fileutils'
require 'stringio'
require 'zlib'
require 'zip/stdrubyext'
require 'zip/ioextras'
if Tempfile.superclass == SimpleDelegator
require 'zip/tempfile_bugfixed'
Tempfile = BugFix::Tempfile
end
module Zlib #:nodoc:all
if ! const_defined? :MAX_WBITS
MAX_WBITS = Zlib::Deflate.MAX_WBITS
end
end
module Zip
VERSION = '0.9.4'
RUBY_MINOR_VERSION = RUBY_VERSION.split(".")[1].to_i
RUNNING_ON_WINDOWS = /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
# Ruby 1.7.x compatibility
# In ruby 1.6.x and 1.8.0 reading from an empty stream returns
# an empty string the first time and then nil.
# not so in 1.7.x
EMPTY_FILE_RETURNS_EMPTY_STRING_FIRST = RUBY_MINOR_VERSION != 7
# ZipInputStream is the basic class for reading zip entries in a
# zip file. It is possible to create a ZipInputStream object directly,
# passing the zip file name to the constructor, but more often than not
# the ZipInputStream will be obtained from a ZipFile (perhaps using the
# ZipFileSystem interface) object for a particular entry in the zip
# archive.
#
# A ZipInputStream inherits IOExtras::AbstractInputStream in order
# to provide an IO-like interface for reading from a single zip
# entry. Beyond methods for mimicking an IO-object it contains
# the method get_next_entry for iterating through the entries of
# an archive. get_next_entry returns a ZipEntry object that describes
# the zip entry the ZipInputStream is currently reading from.
#
# Example that creates a zip archive with ZipOutputStream and reads it
# back again with a ZipInputStream.
#
# require 'zip/zip'
#
# Zip::ZipOutputStream::open("my.zip") {
# |io|
#
# io.put_next_entry("first_entry.txt")
# io.write "Hello world!"
#
# io.put_next_entry("adir/first_entry.txt")
# io.write "Hello again!"
# }
#
#
# Zip::ZipInputStream::open("my.zip") {
# |io|
#
# while (entry = io.get_next_entry)
# puts "Contents of #{entry.name}: '#{io.read}'"
# end
# }
#
# java.util.zip.ZipInputStream is the original inspiration for this
# class.
class ZipInputStream
include IOExtras::AbstractInputStream
# Opens the indicated zip file. An exception is thrown
# if the specified offset in the specified filename is
# not a local zip entry header.
def initialize(filename, offset = 0)
super()
@archiveIO = File.open(filename, "rb")
@archiveIO.seek(offset, IO::SEEK_SET)
@decompressor = NullDecompressor.instance
@currentEntry = nil
end
def close
@archiveIO.close
end
# Same as #initialize but if a block is passed the opened
# stream is passed to the block and closed when the block
# returns.
def ZipInputStream.open(filename)
return new(filename) unless block_given?
zio = new(filename)
yield zio
ensure
zio.close if zio
end
# Returns a ZipEntry object. It is necessary to call this
# method on a newly created ZipInputStream before reading from
# the first entry in the archive. Returns nil when there are
# no more entries.
def get_next_entry
@archiveIO.seek(@currentEntry.next_header_offset,
IO::SEEK_SET) if @currentEntry
open_entry
end
# Rewinds the stream to the beginning of the current entry
def rewind
return if @currentEntry.nil?
@lineno = 0
@archiveIO.seek(@currentEntry.localHeaderOffset,
IO::SEEK_SET)
open_entry
end
# Modeled after IO.sysread
def sysread(numberOfBytes = nil, buf = nil)
@decompressor.sysread(numberOfBytes, buf)
end
def eof
@outputBuffer.empty? && @decompressor.eof
end
alias :eof? :eof
protected
def open_entry
@currentEntry = ZipEntry.read_local_entry(@archiveIO)
if (@currentEntry == nil)
@decompressor = NullDecompressor.instance
elsif @currentEntry.compression_method == ZipEntry::STORED
@decompressor = PassThruDecompressor.new(@archiveIO,
@currentEntry.size)
elsif @currentEntry.compression_method == ZipEntry::DEFLATED
@decompressor = Inflater.new(@archiveIO)
else
raise ZipCompressionMethodError,
"Unsupported compression method #{@currentEntry.compression_method}"
end
flush
return @currentEntry
end
def produce_input
@decompressor.produce_input
end
def input_finished?
@decompressor.input_finished?
end
end
class Decompressor #:nodoc:all
CHUNK_SIZE=32768
def initialize(inputStream)
super()
@inputStream=inputStream
end
end
class Inflater < Decompressor #:nodoc:all
def initialize(inputStream)
super
@zlibInflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
@outputBuffer=""
@hasReturnedEmptyString = ! EMPTY_FILE_RETURNS_EMPTY_STRING_FIRST
end
def sysread(numberOfBytes = nil, buf = nil)
readEverything = (numberOfBytes == nil)
while (readEverything || @outputBuffer.length < numberOfBytes)
break if internal_input_finished?
@outputBuffer << internal_produce_input(buf)
end
return value_when_finished if @outputBuffer.length==0 && input_finished?
endIndex= numberOfBytes==nil ? @outputBuffer.length : numberOfBytes
return @outputBuffer.slice!(0...endIndex)
end
def produce_input
if (@outputBuffer.empty?)
return internal_produce_input
else
return @outputBuffer.slice!(0...(@outputBuffer.length))
end
end
# to be used with produce_input, not read (as read may still have more data cached)
# is data cached anywhere other than @outputBuffer? the comment above may be wrong
def input_finished?
@outputBuffer.empty? && internal_input_finished?
end
alias :eof :input_finished?
alias :eof? :input_finished?
private
def internal_produce_input(buf = nil)
retried = 0
begin
@zlibInflater.inflate(@inputStream.read(Decompressor::CHUNK_SIZE, buf))
rescue Zlib::BufError
raise if (retried >= 5) # how many times should we retry?
retried += 1
retry
end
end
def internal_input_finished?
@zlibInflater.finished?
end
# TODO: Specialize to handle different behaviour in ruby > 1.7.0 ?
def value_when_finished # mimic behaviour of ruby File object.
return nil if @hasReturnedEmptyString
@hasReturnedEmptyString=true
return ""
end
end
class PassThruDecompressor < Decompressor #:nodoc:all
def initialize(inputStream, charsToRead)
super inputStream
@charsToRead = charsToRead
@readSoFar = 0
@hasReturnedEmptyString = ! EMPTY_FILE_RETURNS_EMPTY_STRING_FIRST
end
# TODO: Specialize to handle different behaviour in ruby > 1.7.0 ?
def sysread(numberOfBytes = nil, buf = nil)
if input_finished?
hasReturnedEmptyStringVal=@hasReturnedEmptyString
@hasReturnedEmptyString=true
return "" unless hasReturnedEmptyStringVal
return nil
end
if (numberOfBytes == nil || @readSoFar+numberOfBytes > @charsToRead)
numberOfBytes = @charsToRead-@readSoFar
end
@readSoFar += numberOfBytes
@inputStream.read(numberOfBytes, buf)
end
def produce_input
sysread(Decompressor::CHUNK_SIZE)
end
def input_finished?
(@readSoFar >= @charsToRead)
end
alias :eof :input_finished?
alias :eof? :input_finished?
end
class NullDecompressor #:nodoc:all
include Singleton
def sysread(numberOfBytes = nil, buf = nil)
nil
end
def produce_input
nil
end
def input_finished?
true
end
def eof
true
end
alias :eof? :eof
end
class NullInputStream < NullDecompressor #:nodoc:all
include IOExtras::AbstractInputStream
end
class ZipEntry
STORED = 0
DEFLATED = 8
FSTYPE_FAT = 0
FSTYPE_AMIGA = 1
FSTYPE_VMS = 2
FSTYPE_UNIX = 3
FSTYPE_VM_CMS = 4
FSTYPE_ATARI = 5
FSTYPE_HPFS = 6
FSTYPE_MAC = 7
FSTYPE_Z_SYSTEM = 8
FSTYPE_CPM = 9
FSTYPE_TOPS20 = 10
FSTYPE_NTFS = 11
FSTYPE_QDOS = 12
FSTYPE_ACORN = 13
FSTYPE_VFAT = 14
FSTYPE_MVS = 15
FSTYPE_BEOS = 16
FSTYPE_TANDEM = 17
FSTYPE_THEOS = 18
FSTYPE_MAC_OSX = 19
FSTYPE_ATHEOS = 30
FSTYPES = {
FSTYPE_FAT => 'FAT'.freeze,
FSTYPE_AMIGA => 'Amiga'.freeze,
FSTYPE_VMS => 'VMS (Vax or Alpha AXP)'.freeze,
FSTYPE_UNIX => 'Unix'.freeze,
FSTYPE_VM_CMS => 'VM/CMS'.freeze,
FSTYPE_ATARI => 'Atari ST'.freeze,
FSTYPE_HPFS => 'OS/2 or NT HPFS'.freeze,
FSTYPE_MAC => 'Macintosh'.freeze,
FSTYPE_Z_SYSTEM => 'Z-System'.freeze,
FSTYPE_CPM => 'CP/M'.freeze,
FSTYPE_TOPS20 => 'TOPS-20'.freeze,
FSTYPE_NTFS => 'NTFS'.freeze,
FSTYPE_QDOS => 'SMS/QDOS'.freeze,
FSTYPE_ACORN => 'Acorn RISC OS'.freeze,
FSTYPE_VFAT => 'Win32 VFAT'.freeze,
FSTYPE_MVS => 'MVS'.freeze,
FSTYPE_BEOS => 'BeOS'.freeze,
FSTYPE_TANDEM => 'Tandem NSK'.freeze,
FSTYPE_THEOS => 'Theos'.freeze,
FSTYPE_MAC_OSX => 'Mac OS/X (Darwin)'.freeze,
FSTYPE_ATHEOS => 'AtheOS'.freeze,
}.freeze
attr_accessor :comment, :compressed_size, :crc, :extra, :compression_method,
:name, :size, :localHeaderOffset, :zipfile, :fstype, :externalFileAttributes, :gp_flags, :header_signature
attr_accessor :follow_symlinks
attr_accessor :restore_times, :restore_permissions, :restore_ownership
attr_accessor :unix_uid, :unix_gid, :unix_perms
attr_reader :ftype, :filepath # :nodoc:
# Returns the character encoding used for name and comment
def name_encoding
(@gp_flags & 0b100000000000) != 0 ? "utf8" : "CP437//"
end
# Returns the name in the encoding specified by enc
def name_in(enc)
Iconv.conv(enc, name_encoding, @name)
end
# Returns the name in the encoding specified by enc
def comment_in(enc)
Iconv.conv(enc, name_encoding, @name)
end
def initialize(zipfile = "", name = "", comment = "", extra = "",
compressed_size = 0, crc = 0,
compression_method = ZipEntry::DEFLATED, size = 0,
time = Time.now)
super()
if name.starts_with("/")
raise ZipEntryNameError, "Illegal ZipEntry name '#{name}', name must not start with /"
end
@localHeaderOffset = 0
@local_header_size = 0
@internalFileAttributes = 1
@externalFileAttributes = 0
@version = 52 # this library's version
@ftype = nil # unspecified or unknown
@filepath = nil
if Zip::RUNNING_ON_WINDOWS
@fstype = FSTYPE_FAT
else
@fstype = FSTYPE_UNIX
end
@zipfile = zipfile
@comment = comment
@compressed_size = compressed_size
@crc = crc
@extra = extra
@compression_method = compression_method
@name = name
@size = size
@time = time
@follow_symlinks = false
@restore_times = true
@restore_permissions = false
@restore_ownership = false
# BUG: need an extra field to support uid/gid's
@unix_uid = nil
@unix_gid = nil
@unix_perms = nil
# @posix_acl = nil
# @ntfs_acl = nil
if name_is_directory?
@ftype = :directory
else
@ftype = :file
end
unless ZipExtraField === @extra
@extra = ZipExtraField.new(@extra.to_s)
end
end
def time
if @extra["UniversalTime"]
@extra["UniversalTime"].mtime
else
# Atandard time field in central directory has local time
# under archive creator. Then, we can't get timezone.
@time
end
end
alias :mtime :time
def time=(aTime)
unless @extra.member?("UniversalTime")
@extra.create("UniversalTime")
end
@extra["UniversalTime"].mtime = aTime
@time = aTime
end
# Returns +true+ if the entry is a directory.
def directory?
raise ZipInternalError, "current filetype is unknown: #{self.inspect}" unless @ftype
@ftype == :directory
end
alias :is_directory :directory?
# Returns +true+ if the entry is a file.
def file?
raise ZipInternalError, "current filetype is unknown: #{self.inspect}" unless @ftype
@ftype == :file
end
# Returns +true+ if the entry is a symlink.
def symlink?
raise ZipInternalError, "current filetype is unknown: #{self.inspect}" unless @ftype
@ftype == :symlink
end
def name_is_directory? #:nodoc:all
(%r{\/$} =~ @name) != nil
end
def local_entry_offset #:nodoc:all
localHeaderOffset + @local_header_size
end
def calculate_local_header_size #:nodoc:all
LOCAL_ENTRY_STATIC_HEADER_LENGTH + (@name ? @name.size : 0) + (@extra ? @extra.local_size : 0)
end
def cdir_header_size #:nodoc:all
CDIR_ENTRY_STATIC_HEADER_LENGTH + (@name ? @name.size : 0) +
(@extra ? @extra.c_dir_size : 0) + (@comment ? @comment.size : 0)
end
def next_header_offset #:nodoc:all
local_entry_offset + self.compressed_size
end
# Extracts entry to file destPath (defaults to @name).
def extract(destPath = @name, &onExistsProc)
onExistsProc ||= proc { false }
if directory?
create_directory(destPath, &onExistsProc)
elsif file?
write_file(destPath, &onExistsProc)
elsif symlink?
create_symlink(destPath, &onExistsProc)
else
raise RuntimeError, "unknown file type #{self.inspect}"
end
self
end
def to_s
@name
end
protected
def ZipEntry.read_zip_short(io) # :nodoc:
io.read(2).unpack('v')[0]
end
def ZipEntry.read_zip_long(io) # :nodoc:
io.read(4).unpack('V')[0]
end
public
LOCAL_ENTRY_SIGNATURE = 0x04034b50
LOCAL_ENTRY_STATIC_HEADER_LENGTH = 30
LOCAL_ENTRY_TRAILING_DESCRIPTOR_LENGTH = 4+4+4
VERSION_NEEDED_TO_EXTRACT = 10
def read_local_entry(io) #:nodoc:all
@localHeaderOffset = io.tell
staticSizedFieldsBuf = io.read(LOCAL_ENTRY_STATIC_HEADER_LENGTH)
unless (staticSizedFieldsBuf.size==LOCAL_ENTRY_STATIC_HEADER_LENGTH)
raise ZipError, "Premature end of file. Not enough data for zip entry local header"
end
@header_signature ,
@version ,
@fstype ,
@gp_flags ,
@compression_method,
lastModTime ,
lastModDate ,
@crc ,
@compressed_size ,
@size ,
nameLength ,
extraLength = staticSizedFieldsBuf.unpack('VCCvvvvVVVvv')
unless (@header_signature == LOCAL_ENTRY_SIGNATURE)
raise ZipError, "Zip local header magic not found at location '#{localHeaderOffset}'"
end
set_time(lastModDate, lastModTime)
@name = io.read(nameLength)
extra = io.read(extraLength)
if (extra && extra.length != extraLength)
raise ZipError, "Truncated local zip entry header"
else
if ZipExtraField === @extra
@extra.merge(extra)
else
@extra = ZipExtraField.new(extra)
end
end
@local_header_size = calculate_local_header_size
end
def ZipEntry.read_local_entry(io)
entry = new(io.path)
entry.read_local_entry(io)
return entry
rescue ZipError
return nil
end
def write_local_entry(io) #:nodoc:all
@localHeaderOffset = io.tell
io <<
[LOCAL_ENTRY_SIGNATURE ,
VERSION_NEEDED_TO_EXTRACT , # version needed to extract
0 , # @gp_flags ,
@compression_method ,
@time.to_binary_dos_time , # @lastModTime ,
@time.to_binary_dos_date , # @lastModDate ,
@crc ,
@compressed_size ,
@size ,
@name ? @name.length : 0,
@extra? @extra.local_length : 0 ].pack('VvvvvvVVVvv')
io << @name
io << (@extra ? @extra.to_local_bin : "")
end
CENTRAL_DIRECTORY_ENTRY_SIGNATURE = 0x02014b50
CDIR_ENTRY_STATIC_HEADER_LENGTH = 46
def read_c_dir_entry(io) #:nodoc:all
staticSizedFieldsBuf = io.read(CDIR_ENTRY_STATIC_HEADER_LENGTH)
unless (staticSizedFieldsBuf.size == CDIR_ENTRY_STATIC_HEADER_LENGTH)
raise ZipError, "Premature end of file. Not enough data for zip cdir entry header"
end
@header_signature ,
@version , # version of encoding software
@fstype , # filesystem type
@versionNeededToExtract,
@gp_flags ,
@compression_method ,
lastModTime ,
lastModDate ,
@crc ,
@compressed_size ,
@size ,
nameLength ,
extraLength ,
commentLength ,
diskNumberStart ,
@internalFileAttributes,
@externalFileAttributes,
@localHeaderOffset ,
@name ,
@extra ,
@comment = staticSizedFieldsBuf.unpack('VCCvvvvvVVVvvvvvVV')
unless (@header_signature == CENTRAL_DIRECTORY_ENTRY_SIGNATURE)
raise ZipError, "Zip local header magic not found at location '#{localHeaderOffset}'"
end
set_time(lastModDate, lastModTime)
@name = io.read(nameLength)
if ZipExtraField === @extra
@extra.merge(io.read(extraLength))
else
@extra = ZipExtraField.new(io.read(extraLength))
end
@comment = io.read(commentLength)
unless (@comment && @comment.length == commentLength)
raise ZipError, "Truncated cdir zip entry header"
end
case @fstype
when FSTYPE_UNIX
@unix_perms = (@externalFileAttributes >> 16) & 07777
case (@externalFileAttributes >> 28)
when 04
@ftype = :directory
when 010
@ftype = :file
when 012
@ftype = :symlink
else
raise ZipInternalError, "unknown file type #{'0%o' % (@externalFileAttributes >> 28)}"
end
else
if name_is_directory?
@ftype = :directory
else
@ftype = :file
end
end
@local_header_size = calculate_local_header_size
end
def ZipEntry.read_c_dir_entry(io) #:nodoc:all
entry = new(io.path)
entry.read_c_dir_entry(io)
return entry
rescue ZipError
return nil
end
def file_stat(path) # :nodoc:
if @follow_symlinks
return File::stat(path)
else
return File::lstat(path)
end
end
def get_extra_attributes_from_path(path) # :nodoc:
unless Zip::RUNNING_ON_WINDOWS
stat = file_stat(path)
@unix_uid = stat.uid
@unix_gid = stat.gid
@unix_perms = stat.mode & 07777
end
end
def set_extra_attributes_on_path(destPath) # :nodoc:
return unless (file? or directory?)
case @fstype
when FSTYPE_UNIX
# BUG: does not update timestamps into account
# ignore setuid/setgid bits by default. honor if @restore_ownership
unix_perms_mask = 01777
unix_perms_mask = 07777 if (@restore_ownership)
FileUtils::chmod(@unix_perms & unix_perms_mask, destPath) if (@restore_permissions && @unix_perms)
FileUtils::chown(@unix_uid, @unix_gid, destPath) if (@restore_ownership && @unix_uid && @unix_gid && Process::egid == 0)
# File::utimes()
end
end
def write_c_dir_entry(io) #:nodoc:all
case @fstype
when FSTYPE_UNIX
ft = nil
case @ftype
when :file
ft = 010
@unix_perms ||= 0644
when :directory
ft = 004
@unix_perms ||= 0755
when :symlink
ft = 012
@unix_perms ||= 0755
else
raise ZipInternalError, "unknown file type #{self.inspect}"
end
@externalFileAttributes = (ft << 12 | (@unix_perms & 07777)) << 16
end
io <<
[CENTRAL_DIRECTORY_ENTRY_SIGNATURE,
@version , # version of encoding software
@fstype , # filesystem type
VERSION_NEEDED_TO_EXTRACT , # @versionNeededToExtract ,
0 , # @gp_flags ,
@compression_method ,
@time.to_binary_dos_time , # @lastModTime ,
@time.to_binary_dos_date , # @lastModDate ,
@crc ,
@compressed_size ,
@size ,
@name ? @name.length : 0 ,
@extra ? @extra.c_dir_length : 0 ,
@comment ? comment.length : 0 ,
0 , # disk number start
@internalFileAttributes , # file type (binary=0, text=1)
@externalFileAttributes , # native filesystem attributes
@localHeaderOffset ,
@name ,
@extra ,
@comment ].pack('VCCvvvvvVVVvvvvvVV')
io << @name
io << (@extra ? @extra.to_c_dir_bin : "")
io << @comment
end
def == (other)
return false unless other.class == self.class
# Compares contents of local entry and exposed fields
(@compression_method == other.compression_method &&
@crc == other.crc &&
@compressed_size == other.compressed_size &&
@size == other.size &&
@name == other.name &&
@extra == other.extra &&
@filepath == other.filepath &&
self.time.dos_equals(other.time))
end
def <=> (other)
return to_s <=> other.to_s
end
# Returns an IO like object for the given ZipEntry.
# Warning: may behave weird with symlinks.
def get_input_stream(&aProc)
if @ftype == :directory
return yield(NullInputStream.instance) if block_given?
return NullInputStream.instance
elsif @filepath
case @ftype
when :file
return File.open(@filepath, "rb", &aProc)
when :symlink
linkpath = File::readlink(@filepath)
stringio = StringIO.new(linkpath)
return yield(stringio) if block_given?
return stringio
else
raise "unknown @ftype #{@ftype}"
end
else
zis = ZipInputStream.new(@zipfile, localHeaderOffset)
zis.get_next_entry
if block_given?
begin
return yield(zis)
ensure
zis.close
end
else
return zis
end
end
end
def gather_fileinfo_from_srcpath(srcPath) # :nodoc:
stat = file_stat(srcPath)
case stat.ftype
when 'file'
if name_is_directory?
raise ArgumentError,
"entry name '#{newEntry}' indicates directory entry, but "+
"'#{srcPath}' is not a directory"
end
@ftype = :file
when 'directory'
if ! name_is_directory?
@name += "/"
end
@ftype = :directory
when 'link'
if name_is_directory?
raise ArgumentError,
"entry name '#{newEntry}' indicates directory entry, but "+
"'#{srcPath}' is not a directory"
end
@ftype = :symlink
else
raise RuntimeError, "unknown file type: #{srcPath.inspect} #{stat.inspect}"
end
@filepath = srcPath
get_extra_attributes_from_path(@filepath)
end
def write_to_zip_output_stream(aZipOutputStream) #:nodoc:all
if @ftype == :directory
aZipOutputStream.put_next_entry(self)
elsif @filepath
aZipOutputStream.put_next_entry(self)
get_input_stream { |is| IOExtras.copy_stream(aZipOutputStream, is) }
else
aZipOutputStream.copy_raw_entry(self)
end
end
def parent_as_string
entry_name = name.chomp("/")
slash_index = entry_name.rindex("/")
slash_index ? entry_name.slice(0, slash_index+1) : nil
end
def get_raw_input_stream(&aProc)
File.open(@zipfile, "rb", &aProc)
end
private
def set_time(binaryDosDate, binaryDosTime)
@time = Time.parse_binary_dos_format(binaryDosDate, binaryDosTime)
rescue ArgumentError
puts "Invalid date/time in zip entry"
end
def write_file(destPath, continueOnExistsProc = proc { false })
if File.exists?(destPath) && ! yield(self, destPath)
raise ZipDestinationFileExistsError,
"Destination '#{destPath}' already exists"
end
File.open(destPath, "wb") do |os|
get_input_stream do |is|
set_extra_attributes_on_path(destPath)
buf = ''
while buf = is.sysread(Decompressor::CHUNK_SIZE, buf)
os << buf
end
end
end
end
def create_directory(destPath)
if File.directory? destPath
return
elsif File.exists? destPath
if block_given? && yield(self, destPath)
FileUtils::rm_f destPath
else
raise ZipDestinationFileExistsError,
"Cannot create directory '#{destPath}'. "+
"A file already exists with that name"
end
end
Dir.mkdir destPath
set_extra_attributes_on_path(destPath)
end
# BUG: create_symlink() does not use &onExistsProc
def create_symlink(destPath)
stat = nil
begin
stat = File::lstat(destPath)
rescue Errno::ENOENT
end
io = get_input_stream
linkto = io.read
if stat
if stat.symlink?
if File::readlink(destPath) == linkto
return
else
raise ZipDestinationFileExistsError,
"Cannot create symlink '#{destPath}'. "+
"A symlink already exists with that name"
end
else
raise ZipDestinationFileExistsError,
"Cannot create symlink '#{destPath}'. "+
"A file already exists with that name"
end
end
File::symlink(linkto, destPath)
end
end
# ZipOutputStream is the basic class for writing zip files. It is
# possible to create a ZipOutputStream object directly, passing
# the zip file name to the constructor, but more often than not
# the ZipOutputStream will be obtained from a ZipFile (perhaps using the
# ZipFileSystem interface) object for a particular entry in the zip
# archive.
#
# A ZipOutputStream inherits IOExtras::AbstractOutputStream in order
# to provide an IO-like interface for writing to a single zip
# entry. Beyond methods for mimicking an IO-object it contains
# the method put_next_entry that closes the current entry
# and creates a new.
#
# Please refer to ZipInputStream for example code.
#
# java.util.zip.ZipOutputStream is the original inspiration for this
# class.
class ZipOutputStream
include IOExtras::AbstractOutputStream
attr_accessor :comment
# Opens the indicated zip file. If a file with that name already
# exists it will be overwritten.
def initialize(fileName)
super()
@fileName = fileName
@outputStream = File.new(@fileName, "wb")
@entrySet = ZipEntrySet.new
@compressor = NullCompressor.instance
@closed = false
@currentEntry = nil
@comment = nil
end
# Same as #initialize but if a block is passed the opened
# stream is passed to the block and closed when the block
# returns.
def ZipOutputStream.open(fileName)
return new(fileName) unless block_given?
zos = new(fileName)
yield zos
ensure
zos.close if zos
end
# Closes the stream and writes the central directory to the zip file
def close
return if @closed
finalize_current_entry
update_local_headers
write_central_directory
@outputStream.close
@closed = true
end
# Closes the current entry and opens a new for writing.
# +entry+ can be a ZipEntry object or a string.
def put_next_entry(entryname, comment = nil, extra = nil, compression_method = ZipEntry::DEFLATED, level = Zlib::DEFAULT_COMPRESSION)
raise ZipError, "zip stream is closed" if @closed
new_entry = ZipEntry.new(@fileName, entryname.to_s)
new_entry.comment = comment if !comment.nil?
if (!extra.nil?)
new_entry.extra = ZipExtraField === extra ? extra : ZipExtraField.new(extra.to_s)
end
new_entry.compression_method = compression_method
init_next_entry(new_entry, level)
@currentEntry = new_entry
end
def copy_raw_entry(entry)
entry = entry.dup
raise ZipError, "zip stream is closed" if @closed
raise ZipError, "entry is not a ZipEntry" if !entry.kind_of?(ZipEntry)
finalize_current_entry
@entrySet << entry
src_pos = entry.local_entry_offset
entry.write_local_entry(@outputStream)
@compressor = NullCompressor.instance