ziperu 0.2.2-x86_64-linux-gnu → 0.3.0-x86_64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +197 -0
  3. data/README.md +51 -31
  4. data/lib/zip.rb +3 -3
  5. data/lib/ziperu/3.1/ziperu.so +0 -0
  6. data/lib/ziperu/3.2/ziperu.so +0 -0
  7. data/lib/ziperu/3.3/ziperu.so +0 -0
  8. data/lib/ziperu/3.4/ziperu.so +0 -0
  9. data/lib/ziperu/4.0/ziperu.so +0 -0
  10. data/lib/ziperu/central_directory.rb +4 -8
  11. data/lib/ziperu/constants.rb +8 -0
  12. data/lib/ziperu/crypto.rb +10 -2
  13. data/lib/ziperu/dos_time.rb +1 -1
  14. data/lib/ziperu/entry/source.rb +6 -0
  15. data/lib/ziperu/entry.rb +275 -107
  16. data/lib/ziperu/entry_set.rb +0 -5
  17. data/lib/ziperu/errors.rb +4 -2
  18. data/lib/ziperu/extra_field/zip64.rb +1 -3
  19. data/lib/ziperu/extra_field.rb +10 -10
  20. data/lib/ziperu/file/commit.rb +255 -0
  21. data/lib/ziperu/file/extraction.rb +280 -0
  22. data/lib/ziperu/file.rb +52 -363
  23. data/lib/ziperu/file_split.rb +1 -3
  24. data/lib/ziperu/filesystem/dir.rb +3 -9
  25. data/lib/ziperu/filesystem/file.rb +2 -6
  26. data/lib/ziperu/filesystem/zip_file_name_mapper.rb +2 -2
  27. data/lib/ziperu/input_stream.rb +48 -36
  28. data/lib/ziperu/ioextras/abstract_input_stream.rb +83 -31
  29. data/lib/ziperu/ioextras/abstract_output_stream.rb +1 -3
  30. data/lib/ziperu/ioextras/fake_io.rb +1 -3
  31. data/lib/ziperu/ioextras.rb +6 -0
  32. data/lib/ziperu/limits.rb +48 -0
  33. data/lib/ziperu/null_input_stream.rb +1 -1
  34. data/lib/ziperu/output_stream.rb +127 -30
  35. data/lib/ziperu/pass_thru_decompressor.rb +1 -3
  36. data/lib/ziperu/rails_streaming.rb +5 -5
  37. data/lib/ziperu/remote_io.rb +181 -32
  38. data/lib/ziperu/size_estimator.rb +27 -19
  39. data/lib/ziperu/streamable_stream.rb +110 -10
  40. data/lib/ziperu/verify_report.rb +62 -0
  41. data/lib/ziperu/version.rb +2 -2
  42. data/lib/ziperu.rb +19 -17
  43. metadata +7 -2
data/lib/ziperu/entry.rb CHANGED
@@ -24,8 +24,24 @@ module Ziperu
24
24
  XZ = ::Ziperu::COMPRESSION_METHOD_XZ
25
25
  PPMD = ::Ziperu::COMPRESSION_METHOD_PPMD
26
26
 
27
- # Language encoding flag (EFS) bit
28
- EFS = 0b100000000000 # :nodoc:
27
+ # General-purpose flag bits: the entry is encrypted; its sizes and CRC
28
+ # follow the data (it was written in streaming mode); its name and
29
+ # comment are UTF-8 (the language encoding flag, EFS).
30
+ ENCRYPTED_GPFLAG = 0b1 # :nodoc:
31
+ DATA_DESCRIPTOR_GPFLAG = 0b1000 # :nodoc:
32
+ EFS = 0b100000000000 # :nodoc:
33
+
34
+ # The permission bits of a Unix mode, and those kept when ownership is
35
+ # not being restored (setuid and setgid are dropped).
36
+ PERMISSION_BITS = 0o7777 # :nodoc:
37
+ SAFE_PERMISSION_BITS = 0o1777 # :nodoc:
38
+
39
+ # How `create_file` opens its file: as 'wb', but where the OS can, not
40
+ # through a link put at the path after it was checked.
41
+ WRITE_NO_FOLLOW = ::File::WRONLY | ::File::CREAT | ::File::TRUNC |
42
+ (defined?(::File::NOFOLLOW) ? ::File::NOFOLLOW : 0) # :nodoc:
43
+ # The same for a replacement written beside the file: always a new one.
44
+ STAGING_FLAGS = (WRITE_NO_FOLLOW & ~::File::TRUNC) | ::File::EXCL # :nodoc:
29
45
 
30
46
  # Compression level flags (bits 1 and 2 of the gp flags).
31
47
  COMPRESSION_LEVEL_SUPERFAST_GPFLAG = 0b110 # :nodoc:
@@ -104,10 +120,21 @@ module Ziperu
104
120
  # The central directory's extra fields, parsed on first use: most
105
121
  # entries of a large archive are only ever listed.
106
122
  def parsed_extra
107
- @extra ||= ExtraField.new(@extra_raw)
123
+ @extra ||= ExtraField.new(@extra_raw) # rubocop:disable Naming/MemoizedInstanceVariableName
108
124
  end
109
125
  private :parsed_extra
110
126
 
127
+ # The fields as far as the central directory has them (with any local
128
+ # ones already merged in, and edits), or nil when it has none: no
129
+ # local header is read.
130
+ def central_extra
131
+ return @extra if @extra
132
+ return nil if @extra_raw.nil? || @extra_raw.empty?
133
+
134
+ parsed_extra
135
+ end
136
+ private :central_extra
137
+
111
138
  # Whether the extra fields differ from what the archive holds. Such an
112
139
  # edit is written whenever the archive is next committed, but does not
113
140
  # call for a commit by itself, as in rubyzip: `FileSystem#chown` edits
@@ -125,10 +152,24 @@ module Ziperu
125
152
  # Ziperu::File has released it (rubyzip lets entries be read after `close`).
126
153
  def archive # :nodoc:
127
154
  @source.native(@local_header_offset)
128
- end
155
+ end # :nodoc:
129
156
 
130
157
  attr_writer :size # :nodoc:
131
158
 
159
+ # What the data of an entry read from a stream comes to: unknown (a
160
+ # nil size) until it has been read, when its header leaves that to the
161
+ # descriptor. Not an edit, so the entry is not marked dirty.
162
+ def learn_data(size, crc) # :nodoc:
163
+ @size = size
164
+ @crc = crc
165
+ end
166
+
167
+ # Reads from `native` from now on, which holds the entry's record at
168
+ # the same index (see Ziperu::File#refresh_after_append).
169
+ def rebind_native(native) # :nodoc:
170
+ @source.rebind(native)
171
+ end
172
+
132
173
  # Index of the entry in the archive's central directory, or nil for an
133
174
  # entry that is not (yet) in an archive, or that the native core cannot
134
175
  # address by index: one of several records under the same name, which
@@ -147,8 +188,8 @@ module Ziperu
147
188
 
148
189
  def comment=(comment)
149
190
  comment = comment.to_s
150
- if comment.bytesize > 0xFFFF
151
- raise Error, "entry comment is #{comment.bytesize} bytes; the limit is 65535"
191
+ if comment.bytesize > MAX_FIELD_LENGTH
192
+ raise Error, "entry comment is #{comment.bytesize} bytes; the limit is #{MAX_FIELD_LENGTH}"
152
193
  end
153
194
 
154
195
  @comment = comment
@@ -214,14 +255,26 @@ module Ziperu
214
255
  # Build an entry from the metadata Hash the native core produces for
215
256
  # one central-directory record.
216
257
  def self.from_meta(archive, meta, zipfile = nil, metadata_encoding: nil, settings: ::Ziperu) # :nodoc:
258
+ from_row(archive, meta.values_at(*ROW_FIELDS), zipfile, metadata_encoding: metadata_encoding,
259
+ settings: settings)
260
+ end
261
+
262
+ # The fields of a row from `Native::Archive#each_entry_row`, in order:
263
+ # what `from_meta`'s Hash holds under these keys. In a row an empty
264
+ # comment or extra field may be nil.
265
+ ROW_FIELDS = %i[index name size compressed_size crc compression_method flags external_attributes
266
+ fstype version_made_by dos_date dos_time comment extra header_offset].freeze # :nodoc:
267
+
268
+ # Build an entry from one row (see ROW_FIELDS).
269
+ def self.from_row(archive, row, zipfile = nil, metadata_encoding: nil, settings: ::Ziperu) # :nodoc:
217
270
  entry = allocate
218
- entry.send(:init_from_meta, archive, meta, zipfile, metadata_encoding, settings)
271
+ entry.send(:init_from_row, archive, row, zipfile, metadata_encoding, settings)
219
272
  entry
220
273
  end
221
274
 
222
275
  # Is this entry encrypted?
223
276
  def encrypted?
224
- gp_flags & 1 == 1
277
+ gp_flags.anybits?(ENCRYPTED_GPFLAG)
225
278
  end
226
279
 
227
280
  # Encrypted with the traditional PKWARE cipher (anything but AES).
@@ -233,7 +286,7 @@ module Ziperu
233
286
  # Only informational here: reading goes through the central directory,
234
287
  # so an incomplete local header does not stop `get_input_stream`.
235
288
  def incomplete? # :nodoc:
236
- (gp_flags & 8 == 8) && (crc == 0 || size == 0 || compressed_size == 0)
289
+ gp_flags.anybits?(DATA_DESCRIPTOR_GPFLAG) && (crc == 0 || size == 0 || compressed_size == 0)
237
290
  end
238
291
 
239
292
  # Was a size given, or is it still unknown (as for an entry that is
@@ -249,12 +302,20 @@ module Ziperu
249
302
 
250
303
  # Get a timestamp component of this entry. Returns modification time by
251
304
  # default.
305
+ #
306
+ # The modification time comes from the central directory's fields,
307
+ # which carry it in full, as rubyzip reads it; the access and creation
308
+ # times are only in the local header's, which is read for them. Listing
309
+ # the times of a large archive so reads no local header.
252
310
  def time(component: :mtime)
311
+ fields = component == :mtime ? central_extra : extra
253
312
  time =
254
- if extra[:universaltime]
255
- extra[:universaltime].send(component)
256
- elsif extra[:ntfs]
257
- extra[:ntfs].send(component)
313
+ if fields.nil?
314
+ nil
315
+ elsif fields[:universaltime]
316
+ fields[:universaltime].send(component)
317
+ elsif fields[:ntfs]
318
+ fields[:ntfs].send(component)
258
319
  end
259
320
 
260
321
  time || (stored_time if component == :mtime)
@@ -285,13 +346,11 @@ module Ziperu
285
346
 
286
347
  def time=(value, component: :mtime)
287
348
  mark_dirty!(:time=)
288
- unless extra.member?(:universaltime) || extra.member?(:ntfs)
289
- extra.create(:universaltime)
290
- end
349
+ extra.create(:universaltime) unless extra.member?(:universaltime) || extra.member?(:ntfs)
291
350
 
292
351
  value = DOSTime.from_time(value)
293
- comp = "#{component}=" unless component.to_s.end_with?('=')
294
- (extra[:universaltime] || extra[:ntfs]).send(comp, value)
352
+ setter = component.to_s.end_with?('=') ? component : "#{component}="
353
+ (extra[:universaltime] || extra[:ntfs]).send(setter, value)
295
354
  @time = value if component == :mtime
296
355
  end
297
356
 
@@ -307,7 +366,8 @@ module Ziperu
307
366
 
308
367
  # Does this entry return time fields with accurate timezone information?
309
368
  def absolute_time?
310
- extra.member?(:universaltime) || extra.member?(:ntfs)
369
+ fields = central_extra
370
+ !fields.nil? && (fields.member?(:universaltime) || fields.member?(:ntfs))
311
371
  end
312
372
 
313
373
  # Returns STORED if the entry is a directory or the compression level is 0.
@@ -410,6 +470,13 @@ module Ziperu
410
470
  # NB: The caller is responsible for making sure `destination_directory` is
411
471
  # safe, if it is passed.
412
472
  #
473
+ # Below `destination_directory` nothing is written through a link
474
+ # already on disk (a symlink, or a junction on Windows): an entry with
475
+ # one on the way, or at its own path, is skipped with a warning. The
476
+ # destination itself may be a link. The check is made just before the
477
+ # path is used, so it does not hold against a local user who swaps a
478
+ # directory for a link while the extraction runs.
479
+ #
413
480
  # `create_parent_directories`, if true, creates any missing intermediate
414
481
  # directories for a file entry before writing it. This defaults to
415
482
  # false: a missing intermediate directory usually means an earlier
@@ -435,6 +502,13 @@ module Ziperu
435
502
  return self
436
503
  end
437
504
 
505
+ # A symlink entry replaces a link at its own path; nothing else is
506
+ # written through one.
507
+ if (link = link_on_the_way(dest_dir, extract_path, leaf: !symlink?))
508
+ warn "WARNING: skipped extracting '#{@name}' through the link '#{link}'."
509
+ return self
510
+ end
511
+
438
512
  block ||= Entry.on_exists_block(on_exists, @settings)
439
513
 
440
514
  raise "unknown file type #{inspect}" unless directory? || file? || symlink?
@@ -462,7 +536,7 @@ module Ziperu
462
536
  end
463
537
  end
464
538
 
465
- # The native extractor's code for the policy; nil when a block decides.
539
+ # The native extractor's code for the policy.
466
540
  def self.on_exists_code(policy) # :nodoc:
467
541
  { raise: 0, overwrite: 1, skip: 2 }.fetch(policy) do
468
542
  raise ArgumentError, "on_exists: takes :raise, :overwrite or :skip, not #{policy.inspect}"
@@ -492,21 +566,13 @@ module Ziperu
492
566
  stat = file_stat(src_path)
493
567
  @ftype = case stat.ftype
494
568
  when 'file'
495
- if name_is_directory?
496
- raise ArgumentError,
497
- "entry name '#{@name}' indicates a directory entry, but " \
498
- "'#{src_path}' is not a directory"
499
- end
569
+ check_not_directory_name!(src_path)
500
570
  :file
501
571
  when 'directory'
502
572
  @name += '/' unless name_is_directory?
503
573
  :directory
504
574
  when 'link'
505
- if name_is_directory?
506
- raise ArgumentError,
507
- "entry name '#{@name}' indicates a directory entry, but " \
508
- "'#{src_path}' is not a directory"
509
- end
575
+ check_not_directory_name!(src_path)
510
576
  :symlink
511
577
  else
512
578
  raise "unknown file type: #{src_path.inspect} #{stat.inspect}"
@@ -554,17 +620,41 @@ module Ziperu
554
620
  zip_output_stream.put_next_entry(self)
555
621
  when :restream
556
622
  zip_output_stream.put_next_entry(self)
557
- get_input_stream do |is|
558
- ::Ziperu::IOExtras.copy_stream(zip_output_stream, is)
623
+ if (path = native_source_path)
624
+ zip_output_stream.write_file(path)
625
+ else
626
+ get_input_stream do |is|
627
+ ::Ziperu::IOExtras.copy_stream(zip_output_stream, is)
628
+ end
559
629
  end
560
630
  when :copy_encrypted
561
631
  zip_output_stream.copy_encrypted_entry(self)
562
632
  else
563
- renamed = @name.b != @original_name.b.tr('\\', '/')
633
+ renamed = renamed?
564
634
  zip_output_stream.copy_raw_entry(self, (@name if renamed), touch: dirty? && !renamed)
565
635
  end
566
636
  end
567
637
 
638
+ # The file on disk a regular file entry added from a path is written
639
+ # from, when the native core can open it by name; nil otherwise.
640
+ def native_source_path # :nodoc:
641
+ return nil unless pending_data? && ftype == :file
642
+
643
+ path = @source.path
644
+ return nil unless path
645
+
646
+ path = path.to_path if path.respond_to?(:to_path)
647
+ path = path.to_s
648
+ path if IOExtras.native_text?(path)
649
+ end
650
+
651
+ # Whether committing the entry is a raw copy of it as it is: no new
652
+ # name, nothing touched, not ZipCrypto (see `write_to_zip_output_stream`).
653
+ # Such entries are copied in runs (OutputStream#put_entries).
654
+ def plain_raw_copy? # :nodoc:
655
+ write_plan == :copy_raw && !dirty? && !renamed?
656
+ end
657
+
568
658
  # How the entry reaches an output stream: `:header` for a directory or
569
659
  # a symlink (nothing to stream), `:restream` to decompress and write
570
660
  # afresh (a new entry, or one edited beyond what a raw copy carries),
@@ -612,7 +702,25 @@ module Ziperu
612
702
  end
613
703
 
614
704
  def loses_fields_on_raw_copy? # :nodoc:
615
- restreamable? && (extra.keys & RAW_COPY_LOSES).any?
705
+ return false unless restreamable?
706
+ # Asked of the whole archive at once before a commit (see
707
+ # File#learn_raw_copy_losses), for an entry whose fields are as read.
708
+ return @raw_copy_loses if !@raw_copy_loses.nil? && !@local_extra_merged
709
+
710
+ extra.keys.intersect?(RAW_COPY_LOSES)
711
+ end
712
+
713
+ # The header IDs of RAW_COPY_LOSES, for the native core.
714
+ RAW_COPY_LOSES_IDS = [0x5455, 0x000A, 0x5855, 0x7855].freeze # :nodoc:
715
+
716
+ attr_writer :raw_copy_loses # :nodoc:
717
+
718
+ # Whether appending to the archive, which leaves this entry's local
719
+ # header alone but has the crate write its central record again,
720
+ # would lose fields of that record.
721
+ def central_fields_lost_on_append? # :nodoc:
722
+ fields = central_extra
723
+ !fields.nil? && restreamable? && fields.keys.intersect?(RAW_COPY_LOSES)
616
724
  end
617
725
 
618
726
  # Whether the writer can decompress and rewrite the entry: it is not
@@ -674,10 +782,9 @@ module Ziperu
674
782
 
675
783
  @unix_uid = stat.uid
676
784
  @unix_gid = stat.gid
677
- @unix_perms = stat.mode & 0o7777
785
+ @unix_perms = stat.mode & PERMISSION_BITS
678
786
  end
679
787
 
680
- # Decompressed contents as a binary String, in one native call.
681
788
  # Yields (or returns) an IO over the whole archive this entry is in,
682
789
  # as rubyzip does: a fresh File for an archive on disk, the buffer
683
790
  # itself (rewound) for one in memory.
@@ -715,8 +822,10 @@ module Ziperu
715
822
  @source.local_extra(@local_header_offset).bytesize
716
823
  end
717
824
 
825
+ # Decompressed contents as a binary String, in one native call.
718
826
  def get_raw_input_string # :nodoc:
719
827
  return ''.b if ftype == :directory
828
+
720
829
  check_in_archive!(archive)
721
830
  # A record without an index is read through the stream.
722
831
  return open_input_stream(enforce_size: true, &:read) if index.nil?
@@ -743,6 +852,19 @@ module Ziperu
743
852
 
744
853
  private
745
854
 
855
+ # Whether the entry's name is no longer the one the archive has it under.
856
+ def renamed?
857
+ @name.b != @original_name.b.tr('\\', '/')
858
+ end
859
+
860
+ def check_not_directory_name!(src_path)
861
+ return unless name_is_directory?
862
+
863
+ raise ArgumentError,
864
+ "entry name '#{@name}' indicates a directory entry, but " \
865
+ "'#{src_path}' is not a directory"
866
+ end
867
+
746
868
  # Like get_input_stream, with `enforce_size: false` reading past a
747
869
  # declared size that is too small (what rubyzip does when
748
870
  # Ziperu.validate_entry_sizes is off) instead of stopping at it.
@@ -768,35 +890,59 @@ module Ziperu
768
890
  end
769
891
  end
770
892
 
771
- def create_file(dest_path, _continue_on_exists_proc = proc { Ziperu.continue_on_exists_proc })
772
- if ::File.exist?(dest_path)
893
+ def create_file(dest_path)
894
+ replace = ::File.exist?(dest_path)
895
+ if replace
773
896
  decision = yield(self, dest_path)
774
897
  return if decision == :skip
775
898
  raise DestinationExistsError, dest_path unless decision
776
899
  end
777
900
 
778
- ::File.open(dest_path, 'wb') do |os|
779
- if pending_data?
780
- # Added or replaced from disk or an IO and not yet committed:
781
- # the data is that source's, not the archive's.
782
- get_input_stream { |is| ::IO.copy_stream(is, os) }
783
- else
784
- open_input_stream(decrypter: default_decrypter) do |is|
785
- bytes_written = 0
786
- while (buf = is.sysread(IOExtras::CHUNK_SIZE))
787
- os << buf
788
- bytes_written += buf.bytesize
789
- end
790
- # With enforcement on, the native reader has already raised
791
- # EntrySizeError; without it, warn as rubyzip does.
792
- warn "WARNING: #{EntrySizeError.new(self).message}" if bytes_written > size
793
- end
901
+ # A file being replaced is written beside it and renamed over it once
902
+ # complete, so a failure part-way leaves the original as it was.
903
+ if replace
904
+ staged = staging_path(dest_path)
905
+ done = false
906
+ begin
907
+ ::File.open(staged, STAGING_FLAGS, binmode: true) { |os| write_data_to(os) }
908
+ ::File.rename(staged, dest_path)
909
+ done = true
910
+ ensure
911
+ ::FileUtils.rm_f(staged) unless done
794
912
  end
913
+ else
914
+ ::File.open(dest_path, WRITE_NO_FOLLOW, binmode: true) { |os| write_data_to(os) }
795
915
  end
796
916
 
797
917
  set_extra_attributes_on_path(dest_path)
798
918
  end
799
919
 
920
+ # A hidden name beside `path` for its replacement, on the same file
921
+ # system so the rename stays one step.
922
+ def staging_path(path)
923
+ ::File.join(::File.dirname(path), ".#{::File.basename(path)}.ziperu-#{::Process.pid}-#{rand(1 << 32).to_s(16)}")
924
+ end
925
+
926
+ # The entry's data, decompressed, into `os`.
927
+ def write_data_to(os)
928
+ if pending_data?
929
+ # Added or replaced from disk or an IO and not yet committed:
930
+ # the data is that source's, not the archive's.
931
+ get_input_stream { |is| ::IO.copy_stream(is, os) }
932
+ else
933
+ open_input_stream(decrypter: default_decrypter) do |is|
934
+ bytes_written = 0
935
+ while (buf = is.sysread(IOExtras::CHUNK_SIZE))
936
+ os << buf
937
+ bytes_written += buf.bytesize
938
+ end
939
+ # With enforcement on, the native reader has already raised
940
+ # EntrySizeError; without it, warn as rubyzip does.
941
+ warn "WARNING: #{EntrySizeError.new(self).message}" if bytes_written > size
942
+ end
943
+ end
944
+ end
945
+
800
946
  def create_directory(dest_path)
801
947
  return if ::File.directory?(dest_path)
802
948
 
@@ -812,8 +958,9 @@ module Ziperu
812
958
  set_extra_attributes_on_path(dest_path)
813
959
  end
814
960
 
815
- # Symlinks are never created on extraction: a link pointing outside the
816
- # destination would let a later entry write through it.
961
+ # Created only with `symlinks: :create`, and only when the target
962
+ # resolves inside the destination: a link pointing outside would let a
963
+ # later entry write through it.
817
964
  def create_symlink(dest_path, dest_dir, mode)
818
965
  unless mode == :create
819
966
  warn "WARNING: skipped symlink '#{dest_path}'."
@@ -821,9 +968,8 @@ module Ziperu
821
968
  end
822
969
 
823
970
  target = symlink_target
824
- resolved = ::File.expand_path(target, ::File.dirname(dest_path))
825
- unless resolved.start_with?(dest_dir + ::File::SEPARATOR) || resolved == dest_dir
826
- warn "WARNING: skipped symlink '#{@name}' to '#{target}' as it points outside the destination."
971
+ if (why = symlink_refusal(target, dest_path, dest_dir))
972
+ warn "WARNING: skipped symlink '#{@name}' to '#{target}' as #{why}."
827
973
  return
828
974
  end
829
975
 
@@ -839,12 +985,47 @@ module Ziperu
839
985
  warn "WARNING: could not create symlink '#{dest_path}': #{e.message}"
840
986
  end
841
987
 
988
+ # Why a link to `target` at `dest_path` must not be made under
989
+ # `dest_dir`, or nil when it may.
990
+ def symlink_refusal(target, dest_path, dest_dir)
991
+ resolved = ::File.expand_path(target, ::File.dirname(dest_path))
992
+ unless resolved.start_with?(dest_dir + ::File::SEPARATOR) || resolved == dest_dir
993
+ return 'it points outside the destination'
994
+ end
995
+
996
+ # The check above is lexical. A `..` after a name is not: through a
997
+ # link, `b/..` is the parent of wherever `b` points, so `c -> b/..`
998
+ # with `b -> .` is really the destination's parent. Leading `..`s
999
+ # only climb real directories (the ones on the way were checked).
1000
+ parts = target.split(%r{[/\\]}).reject { |part| part.empty? || part == '.' }
1001
+ "a '..' after a name could lead through a link" if parts.drop_while { |part| part == '..' }.include?('..')
1002
+ end
1003
+ public :symlink_refusal # :nodoc:
1004
+
1005
+ # The first link already on disk below `dest_dir` on the way to `path`,
1006
+ # and at `path` itself when `leaf`, or nil. A junction counts (Ruby's
1007
+ # lstat reports one as a link). The walk stops at the first component
1008
+ # that is missing or not a directory: the callers deal with those.
1009
+ def link_on_the_way(dest_dir, path, leaf: true)
1010
+ parts = path.delete_prefix(dest_dir).split('/').reject(&:empty?)
1011
+ parts.pop unless leaf
1012
+ walked = dest_dir
1013
+ parts.each do |part|
1014
+ walked = ::File.join(walked, part)
1015
+ stat = ::File.lstat(walked)
1016
+ return walked if stat.symlink?
1017
+ return nil unless stat.directory?
1018
+ rescue Errno::ENOENT, Errno::ENOTDIR
1019
+ return nil
1020
+ end
1021
+ nil
1022
+ end
1023
+ public :link_on_the_way # :nodoc:
1024
+
842
1025
  def set_unix_attributes_on_path(dest_path) # :nodoc:
843
1026
  # Ignore setuid/setgid bits by default. Honour if @restore_ownership.
844
- unix_perms_mask = (@restore_ownership ? 0o7777 : 0o1777)
845
- if @restore_permissions && @unix_perms
846
- ::FileUtils.chmod(@unix_perms & unix_perms_mask, dest_path)
847
- end
1027
+ unix_perms_mask = @restore_ownership ? PERMISSION_BITS : SAFE_PERMISSION_BITS
1028
+ ::FileUtils.chmod(@unix_perms & unix_perms_mask, dest_path) if @restore_permissions && @unix_perms
848
1029
  return unless @restore_ownership && @unix_uid && @unix_gid && ::Process.egid == 0
849
1030
 
850
1031
  ::FileUtils.chown(@unix_uid, @unix_gid, dest_path)
@@ -866,15 +1047,8 @@ module Ziperu
866
1047
  @internal_file_attributes = 1
867
1048
  @external_file_attributes = 0
868
1049
 
869
- @version_needed_to_extract = VERSION_NEEDED_TO_EXTRACT
870
- @version = VERSION_MADE_BY
871
-
872
1050
  @ftype = nil
873
- @gp_flags = 0
874
- if @settings.unicode_names
875
- @gp_flags |= EFS
876
- @version = 63
877
- end
1051
+ @gp_flags = @settings.unicode_names ? EFS : 0
878
1052
  @follow_symlinks = false
879
1053
 
880
1054
  @restore_times = DEFAULT_RESTORE_OPTIONS[:restore_times]
@@ -887,10 +1061,12 @@ module Ziperu
887
1061
 
888
1062
  def check_name(name) # :nodoc:
889
1063
  raise EntryNameError, name if name.start_with?('/')
890
- raise EntryNameError if name.length > 65_535
1064
+ raise EntryNameError if name.length > MAX_FIELD_LENGTH
891
1065
  end
892
1066
 
893
- def init_from_meta(archive, meta, zipfile, metadata_encoding = nil, settings = ::Ziperu)
1067
+ def init_from_row(archive, row, zipfile, metadata_encoding, settings)
1068
+ index, name, size, compressed_size, crc, method, flags, external_attributes, fstype, _version,
1069
+ dos_date, dos_time, comment, extra, header_offset = row
894
1070
  @settings = settings
895
1071
  @dirty = false
896
1072
  @zip64 = nil
@@ -902,29 +1078,26 @@ module Ziperu
902
1078
  # they stay binary. A lookup finds a name in any encoding with the
903
1079
  # same bytes. The raw name, before separators are normalised, is what
904
1080
  # the archive knows the entry by.
905
- @gp_flags = meta[:flags]
906
- @original_name = meta[:name]
907
- @source = archive ? Source::Archive.new(archive, zipfile, meta[:index], @original_name) : Source::NONE
908
- @name = decode_stored_text(@original_name.dup, metadata_encoding, meta[:extra])
909
- @name.tr!('\\', '/')
910
- @size = meta[:size]
911
- @compressed_size = meta[:compressed_size]
912
- @crc = meta[:crc]
913
- @compression_method = meta[:compression_method]
914
- @compression_level = @settings.default_compression
915
- @fstype = meta[:fstype]
916
- @version = meta[:version_made_by]
917
- @external_file_attributes = meta[:external_attributes]
918
- set_time(meta[:dos_date], meta[:dos_time])
1081
+ @gp_flags = flags
1082
+ @original_name = name
1083
+ @source = archive ? Source::Archive.new(archive, zipfile, index, @original_name) : Source::NONE
919
1084
  # Most entries have no comment and many no extra fields: those share
920
1085
  # one empty String rather than carrying their own.
921
- comment = meta[:comment]
922
- @comment = comment.empty? ? '' : decode_stored_text(comment, metadata_encoding)
923
1086
  @extra = nil
924
- extra = meta[:extra]
925
- @extra_raw = extra.empty? ? '' : extra
1087
+ @extra_raw = extra.nil? || extra.empty? ? '' : extra
926
1088
  @local_extra_merged = false
927
- @local_header_offset = meta[:header_offset]
1089
+ @name = decode_stored_text(@original_name.dup, metadata_encoding, name: true)
1090
+ @name.tr!('\\', '/')
1091
+ @size = size
1092
+ @compressed_size = compressed_size
1093
+ @crc = crc
1094
+ @compression_method = method
1095
+ @compression_level = @settings.default_compression
1096
+ @fstype = fstype
1097
+ @external_file_attributes = external_attributes
1098
+ set_time(dos_date, dos_time)
1099
+ @comment = comment.nil? || comment.empty? ? '' : decode_stored_text(comment, metadata_encoding)
1100
+ @local_header_offset = header_offset
928
1101
  set_ftype_from_c_dir_entry
929
1102
  end
930
1103
 
@@ -932,16 +1105,16 @@ module Ziperu
932
1105
  # `encoding` is the archive's `metadata_encoding:`, for a name or
933
1106
  # comment stored without the language encoding flag: the bytes are
934
1107
  # read in it and transcoded to UTF-8 (left as bytes when they do not
935
- # decode). `raw_extra`, for a name, is checked for Info-ZIP's Unicode
936
- # Path field first, which carries the UTF-8 name outright.
937
- def decode_stored_text(text, encoding = nil, raw_extra = nil) # :nodoc:
1108
+ # decode). For a name, Info-ZIP's Unicode Path extra field is checked
1109
+ # first, which carries the UTF-8 name outright.
1110
+ def decode_stored_text(text, encoding = nil, name: false) # :nodoc:
938
1111
  forced = @settings.force_entry_names_encoding
939
1112
  if forced
940
1113
  text.force_encoding(forced)
941
1114
  elsif (@gp_flags & EFS).nonzero?
942
1115
  text.force_encoding(::Encoding::UTF_8)
943
1116
  text.force_encoding(::Encoding::BINARY) unless text.valid_encoding?
944
- elsif raw_extra && (utf8 = unicode_path_name(raw_extra, text))
1117
+ elsif name && (utf8 = unicode_path_name(text))
945
1118
  return utf8
946
1119
  elsif encoding
947
1120
  return transcode(text, encoding)
@@ -951,19 +1124,14 @@ module Ziperu
951
1124
 
952
1125
  # The name the Unicode Path extra field carries for `stored`, if there
953
1126
  # is one and it is for this name (its CRC matches).
954
- def unicode_path_name(raw_extra, stored)
955
- return unless raw_extra.include?(ExtraField::UnicodePath::HEADER_ID)
1127
+ # The extra fields are parsed for it now rather than on first use.
1128
+ def unicode_path_name(stored)
1129
+ return unless @extra_raw.include?(ExtraField::UnicodePath::HEADER_ID)
956
1130
 
957
- field = parsed_extra_from(raw_extra)[:unicodepath]
1131
+ field = parsed_extra[:unicodepath]
958
1132
  field.name.dup if field&.for?(stored)
959
1133
  end
960
1134
 
961
- # Parses the central directory's extra fields now rather than on first
962
- # use (the parse is needed for the name).
963
- def parsed_extra_from(raw_extra)
964
- @extra ||= ExtraField.new(raw_extra)
965
- end
966
-
967
1135
  def transcode(text, encoding)
968
1136
  text.force_encoding(encoding).encode(::Encoding::UTF_8)
969
1137
  rescue ::EncodingError, ::ArgumentError
@@ -1007,7 +1175,7 @@ module Ziperu
1007
1175
  def set_ftype_from_c_dir_entry # :nodoc:
1008
1176
  @ftype = case @fstype
1009
1177
  when ::Ziperu::FSTYPE_UNIX
1010
- @unix_perms = (@external_file_attributes >> 16) & 0o7777
1178
+ @unix_perms = (@external_file_attributes >> 16) & PERMISSION_BITS
1011
1179
  case (@external_file_attributes >> 28)
1012
1180
  when ::Ziperu::FILE_TYPE_DIR
1013
1181
  :directory
@@ -1023,7 +1191,7 @@ module Ziperu
1023
1191
  # bits. The native writer stamps the host of the machine it
1024
1192
  # runs on, so archives written here on Windows would lose
1025
1193
  # their permissions on reread; a non-zero mode is kept.
1026
- perms = (@external_file_attributes >> 16) & 0o7777
1194
+ perms = (@external_file_attributes >> 16) & PERMISSION_BITS
1027
1195
  @unix_perms = perms unless perms.zero?
1028
1196
  name_is_directory? ? :directory : :file
1029
1197
  end
@@ -45,7 +45,6 @@ module Ziperu
45
45
  if at
46
46
  @all[at] = entry
47
47
  else
48
- remove_from_all(old) if old
49
48
  @all << entry
50
49
  end
51
50
  end
@@ -84,10 +83,6 @@ module Ziperu
84
83
  entries.reject { |e| shadowed?(e) }
85
84
  end
86
85
 
87
- def each_writable(&block)
88
- writable_entries.each(&block)
89
- end
90
-
91
86
  def size
92
87
  @all.size
93
88
  end
data/lib/ziperu/errors.rb CHANGED
@@ -94,6 +94,8 @@ module Ziperu
94
94
  end
95
95
  end
96
96
 
97
+ # The end-of-central-directory record declares a different number of
98
+ # entries than the central directory holds.
97
99
  class EntryNumberMismatchError < Error
98
100
  def initialize(size, size_in_bytes)
99
101
  super()
@@ -154,13 +156,13 @@ module Ziperu
154
156
 
155
157
  PASSWORD_REQUIRED_MESSAGE = 'A password is required to decode this zip file.'
156
158
 
157
- # Raised by the Rust core where it lacks the domain object a rubyzip
158
- # exception wants; the Ruby layer re-raises the rubyzip-shaped error.
159
159
  # An entry object outlived a commit that moved its record; what it holds
160
160
  # from the central directory is still good, its local header is gone.
161
161
  class EntryMovedError < Error # :nodoc:
162
162
  end
163
163
 
164
+ # Raised by the Rust core where it lacks the domain object a rubyzip
165
+ # exception wants; the Ruby layer re-raises the rubyzip-shaped error.
164
166
  module Native
165
167
  class SizeLimitError < Ziperu::Error; end
166
168
  class PasswordError < Ziperu::Error; end