ziperu 0.3.1 → 0.4.1

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.
@@ -133,6 +133,19 @@ struct Append {
133
133
  tail_start: u64,
134
134
  /// Its bytes, to the end of the file.
135
135
  tail: Vec<u8>,
136
+ /// The archive, for when the writer that held it open is gone.
137
+ path: String,
138
+ }
139
+
140
+ impl Append {
141
+ /// Puts the archive back as it was, through its path: what there is
142
+ /// to do once finishing has failed and taken the writer with it.
143
+ fn restore(&self) -> io::Result<()> {
144
+ let mut file = fs::OpenOptions::new().write(true).open(&self.path)?;
145
+ file.seek(SeekFrom::Start(self.tail_start))?;
146
+ file.write_all(&self.tail)?;
147
+ file.set_len(self.tail_start + self.tail.len() as u64)
148
+ }
136
149
  }
137
150
 
138
151
  struct State {
@@ -142,6 +155,9 @@ struct State {
142
155
  count: usize,
143
156
  crypto: Crypto,
144
157
  append: Option<Append>,
158
+ /// Makes `finish` fail once the archive is written: see
159
+ /// `Writer::fail_finish`.
160
+ fail_finish: bool,
145
161
  }
146
162
 
147
163
  /// Writes below this many bytes keep the GVL (see `Writer::write`).
@@ -259,6 +275,7 @@ impl Writer {
259
275
  base,
260
276
  tail_start,
261
277
  tail,
278
+ path,
262
279
  });
263
280
  }
264
281
  Ok(out)
@@ -856,17 +873,40 @@ impl Writer {
856
873
  /// what a streamed entry came to.
857
874
  pub fn finish(ruby: &Ruby, rb_self: &Self) -> Result<(Option<RString>, RArray), Error> {
858
875
  rb_self.check_broken(ruby)?;
859
- let (zip, crypto, base) = {
876
+ let (zip, crypto, append, fail) = {
860
877
  let mut state = rb_self.borrow(ruby)?;
861
878
  let zip = state.zip.take().ok_or_else(|| closed_error(ruby))?;
862
- let base = state.append.take().map_or(0, |a| a.base);
863
- (zip, std::mem::take(&mut state.crypto), base)
879
+ let append = state.append.take();
880
+ (
881
+ zip,
882
+ std::mem::take(&mut state.crypto),
883
+ append,
884
+ state.fail_finish,
885
+ )
864
886
  };
865
- let (sink, stats) = maybe_without_gvl(rb_self.needs_gvl(), || match zip {
866
- Zip::Seekable(zip) => finish_seekable(zip, crypto),
867
- Zip::Stream(zip, stats) => finish_stream(zip, *stats),
868
- })
869
- .rb(ruby)?;
887
+ let base = append.as_ref().map_or(0, |a| a.base);
888
+ // The old central directory is kept until all of this has worked:
889
+ // writing the new one, reading the archive back, patching headers.
890
+ // A failure anywhere in it has dropped the writer, and with it the
891
+ // only handle, by the time it is known; the archive is put back
892
+ // through its path.
893
+ let outcome = maybe_without_gvl(rb_self.needs_gvl(), || {
894
+ let done = match zip {
895
+ Zip::Seekable(zip) => finish_seekable(zip, crypto),
896
+ Zip::Stream(zip, stats) => finish_stream(zip, *stats),
897
+ };
898
+ let done = match done {
899
+ Ok(_) if fail => Err(ZipError::Io(io::Error::other("finishing was made to fail"))),
900
+ other => other,
901
+ };
902
+ if done.is_err() {
903
+ if let Some(append) = &append {
904
+ let _ = append.restore();
905
+ }
906
+ }
907
+ done
908
+ });
909
+ let (sink, stats) = outcome.rb(ruby)?;
870
910
  let bytes = match sink {
871
911
  Sink::File(_) | Sink::Ruby(_) => None,
872
912
  Sink::Memory(c) => Some(ruby.str_from_slice(&c.into_inner())),
@@ -878,6 +918,13 @@ impl Writer {
878
918
  Ok((bytes, out))
879
919
  }
880
920
 
921
+ /// For the tests: the next `finish` fails after it has written the
922
+ /// archive out, as a full disk or a failing read-back would make it.
923
+ pub fn fail_finish(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
924
+ rb_self.borrow(ruby)?.fail_finish = true;
925
+ Ok(())
926
+ }
927
+
881
928
  pub fn is_closed(&self) -> bool {
882
929
  self.inner.try_borrow().is_ok_and(|s| s.zip.is_none())
883
930
  }
@@ -962,6 +1009,7 @@ impl State {
962
1009
  count: 0,
963
1010
  crypto: Crypto::default(),
964
1011
  append: None,
1012
+ fail_finish: false,
965
1013
  }
966
1014
  }
967
1015
  }
@@ -26,16 +26,23 @@ module Ziperu
26
26
  dirty_fields << field unless dirty_fields.include?(field)
27
27
  end
28
28
 
29
+ # Called before a setter changes anything; raises to refuse the edit.
30
+ def before_edit(_field); end
31
+
29
32
  module ClassMethods # :nodoc:
30
33
  def mark_dirty(*symbols) # :nodoc:
31
- # Move the original method and call it after we've set the dirty flag.
34
+ # Move the original method, and set the dirty flag once it has
35
+ # taken the value: a setter that refuses one changes nothing, and
36
+ # must not leave the object looking edited.
32
37
  symbols.each do |symbol|
33
38
  orig_name = "orig_#{symbol}"
34
39
  alias_method orig_name, symbol
35
40
 
36
41
  define_method(symbol) do |param|
42
+ before_edit(symbol)
43
+ result = send(orig_name, param)
37
44
  mark_dirty!(symbol)
38
- send(orig_name, param)
45
+ result
39
46
  end
40
47
  end
41
48
  end
data/lib/ziperu/entry.rb CHANGED
@@ -9,6 +9,7 @@ module Ziperu
9
9
  # consult the archive by index only for bytes.
10
10
  class Entry
11
11
  include Dirtyable
12
+ include LinkSafety
12
13
 
13
14
  # Constant used to specify that the entry is stored (i.e., not compressed).
14
15
  STORED = ::Ziperu::COMPRESSION_METHOD_STORE
@@ -180,6 +181,13 @@ module Ziperu
180
181
 
181
182
  # Validated here rather than when the archive is written, so a bad
182
183
  # value fails at the call site (rubyzip writes a corrupt header).
184
+ # Raises unless an entry may be called `name`. `File#rename` asks
185
+ # before it moves anything, of whatever kind of entry it holds.
186
+ def self.check_name(name) # :nodoc:
187
+ raise EntryNameError, name if name.start_with?('/')
188
+ raise EntryNameError if name.length > MAX_FIELD_LENGTH
189
+ end
190
+
183
191
  def name=(name)
184
192
  name = name.to_s
185
193
  check_name(name)
@@ -199,6 +207,19 @@ module Ziperu
199
207
  :fstype=, :gp_flags=, :name=, :size=,
200
208
  :unix_gid=, :unix_perms=, :unix_uid=
201
209
 
210
+ # Every setter that edits the entry asks here first, so this is where
211
+ # an entry of an archive opened with `write: false` refuses.
212
+ def before_edit(_field = nil) # :nodoc:
213
+ check_editable!
214
+ end
215
+
216
+ # Raises for an entry of an archive opened read-only.
217
+ def check_editable! # :nodoc:
218
+ return unless @zipfile.kind_of?(::Ziperu::File) && @zipfile.read_only?
219
+
220
+ raise Error, "#{@zipfile.name} was opened read-only (write: false)"
221
+ end
222
+
202
223
  # Create a new Ziperu::Entry.
203
224
  def initialize(
204
225
  zipfile = '', name = '', *legacy,
@@ -355,10 +376,11 @@ module Ziperu
355
376
  end
356
377
 
357
378
  def time=(value, component: :mtime)
379
+ check_editable!
380
+ value = DOSTime.from_time(value)
358
381
  mark_dirty!(:time=)
359
382
  extra.create(:universaltime) unless extra.member?(:universaltime) || extra.member?(:ntfs)
360
383
 
361
- value = DOSTime.from_time(value)
362
384
  setter = component.to_s.end_with?('=') ? component : "#{component}="
363
385
  (extra[:universaltime] || extra[:ntfs]).send(setter, value)
364
386
  @time = value if component == :mtime
@@ -388,6 +410,7 @@ module Ziperu
388
410
  end
389
411
 
390
412
  def compression_method=(method)
413
+ check_editable!
391
414
  @dirty = true
392
415
  @compression_method = (ftype == :directory ? STORED : method)
393
416
  end
@@ -507,7 +530,8 @@ module Ziperu
507
530
  dest_dir = ::File.absolute_path(destination_directory || '.')
508
531
  extract_path = ::File.absolute_path(::File.join(dest_dir, entry_path))
509
532
 
510
- unless extract_path.start_with?(dest_dir + ::File::SEPARATOR) || dest_dir == ::File::SEPARATOR
533
+ inside = extract_path.start_with?(dest_dir + ::File::SEPARATOR) || dest_dir == ::File::SEPARATOR
534
+ unless inside && !IOExtras.windows_stream_name?(entry_path)
511
535
  warn "WARNING: skipped extracting '#{@name}' to '#{extract_path}' as unsafe."
512
536
  return self
513
537
  end
@@ -943,7 +967,7 @@ module Ziperu
943
967
  # A hidden name beside `path` for its replacement, on the same file
944
968
  # system so the rename stays one step.
945
969
  def staging_path(path)
946
- ::File.join(::File.dirname(path), ".#{::File.basename(path)}.ziperu-#{::Process.pid}-#{rand(1 << 32).to_s(16)}")
970
+ IOExtras.staging_path(path, rand(1 << 32).to_s(16))
947
971
  end
948
972
 
949
973
  # The entry's data, decompressed, into `os`.
@@ -1008,43 +1032,6 @@ module Ziperu
1008
1032
  warn "WARNING: could not create symlink '#{dest_path}': #{e.message}"
1009
1033
  end
1010
1034
 
1011
- # Why a link to `target` at `dest_path` must not be made under
1012
- # `dest_dir`, or nil when it may.
1013
- def symlink_refusal(target, dest_path, dest_dir)
1014
- resolved = ::File.expand_path(target, ::File.dirname(dest_path))
1015
- unless resolved.start_with?(dest_dir + ::File::SEPARATOR) || resolved == dest_dir
1016
- return 'it points outside the destination'
1017
- end
1018
-
1019
- # The check above is lexical. A `..` after a name is not: through a
1020
- # link, `b/..` is the parent of wherever `b` points, so `c -> b/..`
1021
- # with `b -> .` is really the destination's parent. Leading `..`s
1022
- # only climb real directories (the ones on the way were checked).
1023
- parts = target.split(%r{[/\\]}).reject { |part| part.empty? || part == '.' }
1024
- "a '..' after a name could lead through a link" if parts.drop_while { |part| part == '..' }.include?('..')
1025
- end
1026
- public :symlink_refusal # :nodoc:
1027
-
1028
- # The first link already on disk below `dest_dir` on the way to `path`,
1029
- # and at `path` itself when `leaf`, or nil. A junction counts (Ruby's
1030
- # lstat reports one as a link). The walk stops at the first component
1031
- # that is missing or not a directory: the callers deal with those.
1032
- def link_on_the_way(dest_dir, path, leaf: true)
1033
- parts = path.delete_prefix(dest_dir).split('/').reject(&:empty?)
1034
- parts.pop unless leaf
1035
- walked = dest_dir
1036
- parts.each do |part|
1037
- walked = ::File.join(walked, part)
1038
- stat = ::File.lstat(walked)
1039
- return walked if stat.symlink?
1040
- return nil unless stat.directory?
1041
- rescue Errno::ENOENT, Errno::ENOTDIR
1042
- return nil
1043
- end
1044
- nil
1045
- end
1046
- public :link_on_the_way # :nodoc:
1047
-
1048
1035
  def set_unix_attributes_on_path(dest_path) # :nodoc:
1049
1036
  # Ignore setuid/setgid bits by default. Honour if @restore_ownership.
1050
1037
  unix_perms_mask = @restore_ownership ? PERMISSION_BITS : SAFE_PERMISSION_BITS
@@ -1083,8 +1070,7 @@ module Ziperu
1083
1070
  end
1084
1071
 
1085
1072
  def check_name(name) # :nodoc:
1086
- raise EntryNameError, name if name.start_with?('/')
1087
- raise EntryNameError if name.length > MAX_FIELD_LENGTH
1073
+ Entry.check_name(name)
1088
1074
  end
1089
1075
 
1090
1076
  def init_from_row(archive, row, zipfile, metadata_encoding, settings, owner)
@@ -51,6 +51,18 @@ module Ziperu
51
51
 
52
52
  alias push <<
53
53
 
54
+ # Puts `fresh` in place of the entries from position `start` on,
55
+ # which it matches name for name: the same entries, read again. One
56
+ # pass, where `<<` would look each one up among all the others.
57
+ def replace_from(start, fresh)
58
+ fresh.each_with_index do |entry, i|
59
+ key = to_key(entry)
60
+ @entry_set[key] = entry if @entry_set[key].equal?(@all[start + i])
61
+ @all[start + i] = entry
62
+ end
63
+ self
64
+ end
65
+
54
66
  # Adds a record read from an archive. Unlike `<<`, an earlier record
55
67
  # of the very same name stays listed (and readable); the lookup by name
56
68
  # finds the later one, as rubyzip's does. Names that only share a key
@@ -9,6 +9,9 @@ module Ziperu
9
9
  # new archive is written beside the old one and renamed over it.
10
10
  def commit
11
11
  return if name.kind_of?(StringIO) || !commit_required?
12
+ # Whatever was changed, and however: an archive opened with
13
+ # `write: false` is not written.
14
+ return if @read_only
12
15
 
13
16
  appended = write_changes
14
17
  # Only now are the changes on disk; until here the entries keep
@@ -113,7 +116,7 @@ module Ziperu
113
116
 
114
117
  kept = @cdir.entries.first(held)
115
118
  kept.each { |e| e.rebind_native(native) }
116
- fresh.each { |e| @cdir << e }
119
+ @cdir.replace_from(held, fresh)
117
120
  @native.close
118
121
  @native = native
119
122
  @dirty = false
@@ -120,6 +120,16 @@ module Ziperu
120
120
  end
121
121
  end
122
122
 
123
+ # Whether `name` matches one of `patterns` (what `exclude:` was given).
124
+ def self.excluded?(patterns, name)
125
+ Array(patterns).any? do |pattern|
126
+ case pattern
127
+ when ::Regexp then pattern.match?(name)
128
+ else ::File.fnmatch?(pattern.to_s, name, ::File::FNM_EXTGLOB | ::File::FNM_DOTMATCH)
129
+ end
130
+ end
131
+ end
132
+
123
133
  # `entries` are the archive's writable entries (of several records
124
134
  # under one name only the last, the one rubyzip would know).
125
135
  def initialize(entries, exclude: nil, junk_paths: false, sanitize: nil)
@@ -190,12 +200,7 @@ module Ziperu
190
200
  # (`File.fnmatch` with `*` crossing `/`, as `unzip -x` has it) or a
191
201
  # Regexp.
192
202
  def excluded?(name)
193
- Array(@exclude).any? do |pattern|
194
- case pattern
195
- when ::Regexp then pattern.match?(name)
196
- else ::File.fnmatch?(pattern.to_s, name, ::File::FNM_EXTGLOB | ::File::FNM_DOTMATCH)
197
- end
198
- end
203
+ self.class.excluded?(@exclude, name)
199
204
  end
200
205
 
201
206
  # The path under the destination an entry goes to.
data/lib/ziperu/file.rb CHANGED
@@ -396,6 +396,9 @@ module Ziperu
396
396
  check_writable!
397
397
  found_entry = get_entry(entry)
398
398
  new_name = new_name.to_path if new_name.respond_to?(:to_path)
399
+ # Before anything is removed: a name the entry cannot take must
400
+ # leave it, and an entry of that name, where they were.
401
+ Entry.check_name(new_name.to_s)
399
402
  check_entry_exists(new_name, continue_on_exists_proc, 'rename')
400
403
  @cdir.delete(found_entry)
401
404
  found_entry.name = new_name
@@ -38,6 +38,24 @@ module Ziperu
38
38
  obj.respond_to?(:to_path) ? obj.to_path : obj.to_s
39
39
  end
40
40
 
41
+ # Whether Windows would take `name`, a path below a destination,
42
+ # for something other than a file there: with a colon it is a
43
+ # stream of a file ("a.txt:x" writes into `a.txt`) or a drive.
44
+ def windows_stream_name?(name)
45
+ ::Ziperu::RUNNING_ON_WINDOWS && name.to_s.include?(':')
46
+ end
47
+
48
+ # A hidden name beside `path` for the file that will replace it, in
49
+ # the same directory so that the rename is one step. `tag` tells
50
+ # one from another. The name says which file it is for as far as
51
+ # the 255 bytes a name may have allow.
52
+ def staging_path(path, tag)
53
+ dir, base = ::File.split(path)
54
+ tail = ".ziperu-#{::Process.pid}-#{tag}"
55
+ kept = base.byteslice(0, 254 - tail.bytesize).scrub('')
56
+ ::File.join(dir, ".#{kept}#{tail}")
57
+ end
58
+
41
59
  # Whether the native core can take `str` as a name or path: it wants
42
60
  # valid UTF-8.
43
61
  def native_text?(str)
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ziperu
4
+ # The checks made before a link is created under a destination, and
5
+ # before anything is put where a link on disk could redirect it. Shared
6
+ # by zip and tar extraction.
7
+ module LinkSafety # :nodoc:
8
+ # Why a link to `target` at `dest_path` must not be made under
9
+ # `dest_dir`, or nil when it may.
10
+ def symlink_refusal(target, dest_path, dest_dir)
11
+ resolved = ::File.expand_path(target, ::File.dirname(dest_path))
12
+ unless resolved.start_with?(dest_dir + ::File::SEPARATOR) || resolved == dest_dir
13
+ return 'it points outside the destination'
14
+ end
15
+
16
+ # The check above is lexical. A `..` after a name is not: through a
17
+ # link, `b/..` is the parent of wherever `b` points, so `c -> b/..`
18
+ # with `b -> .` is really the destination's parent. Leading `..`s
19
+ # only climb real directories (the ones on the way were checked).
20
+ parts = target.split(%r{[/\\]}).reject { |part| part.empty? || part == '.' }
21
+ "a '..' after a name could lead through a link" if parts.drop_while { |part| part == '..' }.include?('..')
22
+ end
23
+
24
+ # The first link already on disk below `dest_dir` on the way to `path`,
25
+ # and at `path` itself when `leaf`, or nil. A junction counts (Ruby's
26
+ # lstat reports one as a link). The walk stops at the first component
27
+ # that is missing or not a directory: the callers deal with those.
28
+ def link_on_the_way(dest_dir, path, leaf: true)
29
+ parts = path.delete_prefix(dest_dir).split('/').reject(&:empty?)
30
+ parts.pop unless leaf
31
+ walked = dest_dir
32
+ parts.each do |part|
33
+ walked = ::File.join(walked, part)
34
+ stat = ::File.lstat(walked)
35
+ return walked if stat.symlink?
36
+ return nil unless stat.directory?
37
+ rescue Errno::ENOENT, Errno::ENOTDIR
38
+ return nil
39
+ end
40
+ nil
41
+ end
42
+ end
43
+ end
@@ -102,16 +102,18 @@ module Ziperu
102
102
  return new(file_name, **opts) unless block_given?
103
103
 
104
104
  zos = new(file_name, stream: false, **opts)
105
- result =
106
- begin
107
- yield zos
108
- rescue Exception # rubocop:disable Lint/RescueException
109
- # The archive is abandoned: the entries written so far must
110
- # not learn offsets and sizes from it.
111
- zos.abort
112
- raise
113
- end
114
- zos.close
105
+ begin
106
+ result = yield zos
107
+ # Inside the handler too: an append is not over, and can still
108
+ # fail (a comment too long, a disk that fills), until the
109
+ # archive is closed.
110
+ zos.close
111
+ rescue Exception # rubocop:disable Lint/RescueException
112
+ # The archive is abandoned: the entries written so far must
113
+ # not learn offsets and sizes from it.
114
+ zos.abort
115
+ raise
116
+ end
115
117
  result
116
118
  end
117
119
 
@@ -258,12 +260,14 @@ module Ziperu
258
260
  entry = @current_entry
259
261
  raise Error, 'there is no entry being written to take back' if entry.nil? || !@written.last.equal?(entry)
260
262
 
261
- discard_writes
262
263
  if @deferred
263
264
  @deferred = nil
264
265
  else
265
266
  @writer.rollback_entry
266
267
  end
268
+ # Only now: where the entry cannot be taken back (its first bytes
269
+ # have gone out on a stream) what was written to it is still owed.
270
+ discard_writes
267
271
  @written.pop
268
272
  @stream_names&.delete(entry.name.b)
269
273
  @current_entry = nil
@@ -471,6 +475,17 @@ module Ziperu
471
475
  self
472
476
  end
473
477
 
478
+ # Whether a file entry under 4 GiB, with no `zip64:` of its own, is
479
+ # written zip64-ready under `settings`. `unsized` is true for one
480
+ # whose size is not known up front (or that already has the field).
481
+ # The size estimator asks the same question, so the two cannot differ.
482
+ def self.zip64_file?(settings, suppressed: false, unsized: false) # :nodoc:
483
+ return true if settings.write_zip64_support == :always && !suppressed
484
+ return false if suppressed || !settings.write_zip64_support
485
+
486
+ unsized
487
+ end
488
+
474
489
  private
475
490
 
476
491
  # Hands the gathered small writes (see `<<`) to the native writer.
@@ -642,10 +657,8 @@ module Ziperu
642
657
  return true if entry.size >= ZIP64_SIZE_LIMIT || entry.compressed_size >= ZIP64_SIZE_LIMIT
643
658
  return false unless entry.file?
644
659
  return entry.zip64 unless entry.zip64.nil?
645
- return true if @settings.write_zip64_support == :always && !suppressed
646
- return false if suppressed || !@settings.write_zip64_support
647
660
 
648
- entry.zip64? || !entry.size_known?
661
+ self.class.zip64_file?(@settings, suppressed: suppressed, unsized: entry.zip64? || !entry.size_known?)
649
662
  end
650
663
  end
651
664
  end
@@ -90,7 +90,8 @@ module Ziperu
90
90
  def add_file(name, size, compressed_size)
91
91
  fields = default_fields
92
92
  name = name.to_s.b
93
- large = size >= ZIP64_THRESHOLD || compressed_size >= ZIP64_THRESHOLD
93
+ large = size >= ZIP64_THRESHOLD || compressed_size >= ZIP64_THRESHOLD ||
94
+ OutputStream.zip64_file?(@settings)
94
95
  offset_large = @data >= ZIP64_THRESHOLD
95
96
  @entries += 1
96
97
  # The local header, with a zip64 extra for a large entry; the data;