ziperu 0.3.1-aarch64-linux-gnu → 0.4.1-aarch64-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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f52b984b6b6279e50bdf20f3844768e44b0c6607b4022e2ef0ae1a933f67e402
4
- data.tar.gz: f8f0610286732a402c9f324635617013403699e4821a7654990ce4c041e5961c
3
+ metadata.gz: f4eba36fe96c327920c027c4b0ac1d615ff6009003dc8aea0e38480a1481f428
4
+ data.tar.gz: 4ed1508faa5c9cfca26867ad83a20fbb4160cfc09ad523595ec1085abc8ab131
5
5
  SHA512:
6
- metadata.gz: e8828862ee8915daac84d5434e182f590f8e8413de84de99049d6c1659abae0c6126d5fe3fa0dd048f19576e09cee6ea8a920ac72d5a446c4bfc64994652aa72
7
- data.tar.gz: e6ec74cfae72628623a34fe834420d2103e800deef019accb4b912bf63d34445d682e0db9dc148fff8a9543ec3bef7444c2cf499cd3496f1937f0c74f64932f3
6
+ metadata.gz: 52b510426e0e4d984f0d35fa280566e479801362ef3abbbf0ab93088d171fceb2a664172e855794ab3e52d3733ef9b34a9070c7e1cbefa9125a6bfecf7b0fc25
7
+ data.tar.gz: 373f2ea25a029068d7ee41f6f73ec316e1264d413bc2c3dd1e315ba5dd1256ff691778a5954073553eaa342f79f43887527d088527247e5449774b822e434684
data/CHANGELOG.md CHANGED
@@ -1,5 +1,119 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1 (2026-12-06)
4
+
5
+ Fixed:
6
+
7
+ - An archive opened with `write: false` could still be rewritten: a
8
+ setter on one of its entries (`entry.comment = ...`, `name=`, `time=`
9
+ and the rest) marked it changed, and closing the archive wrote it out.
10
+ Those setters now raise `Ziperu::Error` at the call, and a commit of a
11
+ read-only archive writes nothing whatever was changed.
12
+ - `OutputStream#rollback_entry`, refused because the entry's first bytes
13
+ had already gone out on a stream that cannot seek, dropped what was
14
+ still buffered for that entry, so the archive came out with the entry
15
+ short. The data is kept.
16
+ - `File#rename` to a name the entry cannot take (absolute, too long)
17
+ raised only after the entry had been removed, and the next commit
18
+ wrote the archive without it. The name is checked first.
19
+ - An append in place that failed while the archive was being finished
20
+ (an archive comment too long, a disk that filled, a read-back that
21
+ failed) left the archive without a central directory: the saved one
22
+ was let go before the last steps. It is now kept until they are done
23
+ and put back if any fails, and `OutputStream.open(append: true)`
24
+ abandons the append when closing raises.
25
+ - `OutputStream.estimated_size` with `write_zip64_support: :always`
26
+ came out short by the zip64 fields every entry is then written with.
27
+ The estimator and the writer now ask the same question.
28
+ - Committing an append re-read the appended entries in time that grew
29
+ with the square of the archive: 1,000 entries appended to an archive
30
+ of 60,000 took 2.5 s to commit and now take 0.35 s.
31
+ - A file whose name was within about twenty bytes of the 255 a name may
32
+ have could be extracted but not replaced: the replacement is written
33
+ beside it under a longer name, which the file system refused (`File
34
+ name too long`). That stopped a tar archive listing such a name twice,
35
+ an extraction with `on_exists: :overwrite` over such a file, and
36
+ `Ziperu::Tar.create` to an archive so named. The name written beside
37
+ is now cut to fit. Found by the nightly tar fuzzer.
38
+
39
+ ## 0.4.0 (2026-11-21)
40
+
41
+ Added:
42
+
43
+ - `Ziperu::Tar.foreach` and `Ziperu::Tar::Reader` read tar archives:
44
+ plain, or compressed with gzip, zstd, xz or bzip2, told apart by their
45
+ first bytes and not by their name. An archive is read front to back,
46
+ an entry at a time, in constant memory, from a path or from any IO
47
+ with `read` (a pipe, a socket, a response body). An entry gives its
48
+ name, size, type, mode, time (to the nanosecond where the archive has
49
+ it), link target and owner, and its data through `read` and
50
+ `each_chunk`. v7, ustar, GNU and PAX archives are read, long names and
51
+ extended headers included; sparse files and multi-volume archives are
52
+ refused.
53
+ - `Ziperu::Tar.extract_all(path_or_io, dest)` extracts a tar archive
54
+ under the rules a zip is extracted by: a name that resolves outside
55
+ the destination is skipped with a warning, nothing is written through
56
+ a link already on disk, and times and permission bits are restored
57
+ but never setuid, setgid or an owner. Symlinks are skipped unless
58
+ `symlinks: :create`, and then made only when the target stays inside.
59
+ A hard link is made only to a file the same extraction wrote. Devices
60
+ and fifos are skipped. `on_exists:`, `exclude:`, `sanitize:` and
61
+ `progress:` are as for a zip; `strip_components:` drops leading
62
+ directories. Of two entries with one name the last wins, as `tar` has
63
+ it. Links are created after every file.
64
+ - `Ziperu.extract(path_or_io, dest)` extracts a zip or a tar archive,
65
+ told apart by the first bytes, with the options of whichever it is.
66
+ From a pipe a tar archive is streamed; a zip is read into memory
67
+ first, within `max_archive_size`.
68
+ - `Ziperu::Tar.create(path_or_io) { |tar| ... }` writes a tar archive,
69
+ plain or compressed with gzip, zstd, xz or bzip2 (from the file's name,
70
+ or `compression:`, with `level:`). `add` takes a file from disk or any
71
+ IO, `add_data` a String, and there are `mkdir`, `symlink`, `link` and
72
+ `add_recursive`; `Ziperu::Tar.add_recursive(archive, dir)` does a whole
73
+ directory and `Ziperu::Tar.body` gives a Rack body. What is written is
74
+ ustar, with a PAX extended header only for what ustar cannot hold (a
75
+ long or non-ASCII name, a size of 8 GiB or more). It goes to a pipe or
76
+ socket as readily as to a file, and a file is put in place only once
77
+ it is whole. Owners are not recorded, and with `source_date_epoch` the
78
+ same input gives the same bytes.
79
+ - [docs/tar.md](docs/tar.md) describes what is read and written and how
80
+ extraction behaves. CI now exchanges tar archives with GNU tar, bsdtar, Python's
81
+ tarfile and 7-Zip in both directions, and `rake fuzz:tar` fuzzes the
82
+ reader, the extractor and the writer against Python's tarfile.
83
+ - The limits hold for tar as for zip: `max_entries`, `max_entry_size`,
84
+ `max_total_size`, `max_archive_size` for what is read from an IO, and
85
+ `max_compression_ratio`, which is measured over the stream as it is
86
+ read and so stops a compressed bomb a few megabytes in, read or
87
+ skipped.
88
+ - A compressed tar archive is read to the end of its stream, where
89
+ gzip, xz and bzip2 keep their checksum: tar has none for an entry's
90
+ data. A long name or extended header over 1 MiB is refused, and an xz
91
+ stream that asks for more than 256 MiB to decode.
92
+
93
+ Fixed:
94
+
95
+ - On Windows an entry with a colon in its name was written as an
96
+ alternate data stream: `a.txt:x` went into `a.txt`, a file that could
97
+ have been in the destination before and was neither replaced nor
98
+ reported, whatever `on_exists:` said. And `C:x`, a path relative to
99
+ the current directory of drive C, was written there: outside the
100
+ destination. Such an entry is now skipped with a warning, as one that resolves outside the destination is;
101
+ `sanitize: :windows` rewrites the name and extracts it. This was true
102
+ of zip extraction in every release so far.
103
+
104
+ Internal:
105
+
106
+ - The native extractor is in two parts: `placer.rs` decides where an
107
+ entry goes and what is refused on the way (the path check, links on
108
+ disk, what is already there), and `extract.rs` reads zip entries into
109
+ the files it opens. Nothing changes in what is extracted or how.
110
+ - The memory growth check failed a nightly run on code that had passed
111
+ the day before. It sampled resident memory after a full GC, but memory
112
+ glibc had freed and not yet returned swung the samples between 68 and
113
+ 107 MiB. It now calls `malloc_trim` before each sample: the workload
114
+ then sits at 23.8 MiB for all 600 iterations, and the growth allowed
115
+ drops from 8 MiB to 3.
116
+
3
117
  ## 0.3.1 (2026-11-16)
4
118
 
5
119
  Fixed:
data/README.md CHANGED
@@ -19,8 +19,13 @@ the [`zip`](https://github.com/zip-rs/zip2) crate through
19
19
  [Magnus](https://github.com/matsadler/magnus). `require "zip"` aliases
20
20
  `Zip = Ziperu`, so existing code runs unchanged.
21
21
 
22
- ziperu 0.2.3 on GitHub's Linux runners (Ruby 3.4, median of 5), against
23
- rubyzip 3.7.0:
22
+ It also reads, extracts and writes tar archives (`.tar`, `.tar.gz`,
23
+ `.tar.zst`, `.tar.xz`, `.tar.bz2`), extracting under the same safety
24
+ rules, so one gem unpacks whatever was uploaded:
25
+ `Ziperu.extract(upload, "out")`.
26
+
27
+ Measured with ziperu 0.2.3 against rubyzip 3.7.0 on GitHub's Linux
28
+ runners (Ruby 3.4, median of 5 runs):
24
29
 
25
30
  | scenario | rubyzip | ziperu | speedup |
26
31
  |---|---:|---:|---:|
@@ -32,15 +37,17 @@ rubyzip 3.7.0:
32
37
  | append one entry to a 10000-entry archive | 1.16 s | 148 ms | 7.8x |
33
38
  | add 1000 files from disk (`threads: 4`) | 348 ms | 89 ms | 3.9x |
34
39
 
35
- macOS and Windows, every scenario, and which calls release the GVL (what
36
- Puma users ask about) are in [docs/benchmarks.md](docs/benchmarks.md).
40
+ Results for macOS and Windows, and the rest of the scenarios, are in
41
+ [docs/benchmarks.md](docs/benchmarks.md). It also lists which calls
42
+ release the GVL, so other threads (other Puma requests, say) keep running.
37
43
 
38
- - **Precompiled** for Linux (glibc and musl), macOS and Windows, Ruby 3.1 to 4.0. No toolchain, no runtime dependencies.
44
+ - **Precompiled** for Linux (glibc and musl), macOS and Windows, on Ruby 3.3 to 4.0, with binaries for 3.1 and 3.2 as well. No toolchain, no runtime dependencies.
39
45
  - **Fast**: entries inflate and deflate in Rust with the GVL released, the central directory is parsed once, unchanged entries are copied byte for byte on commit, and a commit that only adds entries appends them in place.
40
46
  - **Reads everything**: Stored, Deflate, Deflate64, bzip2, zstd, LZMA, XZ, PPMd and the PKZIP 1.x methods; AES and ZipCrypto. Writes Deflate, Stored, bzip2, zstd, XZ, PPMd, AES and ZipCrypto.
47
+ - **Tar as well**: `Ziperu::Tar` reads and extracts v7, ustar, GNU and PAX archives, plain or compressed with gzip, zstd, xz or bzip2, from a path or any IO including a pipe, and writes them too. See [docs/tar.md](docs/tar.md).
41
48
  - **Safe by default**: no entry inflates past its declared size, extraction skips names that resolve outside the destination and never writes through a link already on disk, symlinks are opt-in, and limits on entry count, entry size, total size and compression ratio can be set up front. [SECURITY.md](SECURITY.md) has the details.
42
49
  - **Friendlier than rubyzip where it costs nothing**: a password on the archive (`File.open(path, password: ...)`), `add` from an IO, Pathname arguments, `File#verify`, progress callbacks, and errors that fail at the call site.
43
- - **Checked against the field**: rubyzip's own test suite, differential fuzzing against Python's `zipfile` and rubyzip, interoperability runs with Info-ZIP, 7-Zip and Python, and the test suites of gems built on rubyzip (roo, caxlsx, rubyXL, docx, write_xlsx, sablon, gepub) run with ziperu in its place.
50
+ - **Checked against the field**: rubyzip's own test suite, differential fuzzing against Python's `zipfile` and rubyzip, interoperability runs with Info-ZIP, 7-Zip, Python, GNU tar and bsdtar, and the test suites of gems built on rubyzip (roo, caxlsx, rubyXL, docx, write_xlsx, sablon, gepub) run with ziperu in its place.
44
51
 
45
52
  ## Installation
46
53
 
@@ -56,9 +63,6 @@ Or on its own:
56
63
  gem install ziperu
57
64
  ```
58
65
 
59
- Precompiled gems ship for Linux, macOS and Windows; see
60
- [Platforms](#platforms) for the details.
61
-
62
66
  ## Quick start
63
67
 
64
68
  ```ruby
@@ -74,28 +78,10 @@ Ziperu::File.open("new.zip", create: true) do |zf|
74
78
  zf.add("report.pdf", "tmp/report.pdf")
75
79
  zf.get_output_stream("notes.txt") { |io| io.puts "written at #{Time.now}" }
76
80
  end
77
-
78
- Ziperu::OutputStream.write_buffer(socket) do |zos| # any IO; a pipe, socket or
79
- zos.put_next_entry("hello.txt") # response body is streamed,
80
- zos.write("hello") # nothing buffered to the end
81
- end
82
-
83
- body = Ziperu::OutputStream.body do |zos| # a Rack body: an Enumerator of
84
- zos.put_next_entry("export.csv") # the archive's bytes, produced
85
- zos.write(csv) # as the server consumes them
86
- end
87
- [200, { "content-type" => "application/zip" }, body]
88
-
89
- Ziperu::File.foreach("huge.zip") do |entry| # one entry at a time, constant
90
- puts entry.name if entry.size > 1 << 30 # memory, however many there are
91
- end
92
-
93
- Ziperu::File.open("secret.zip", password: "s3cret") do |zf| # AES or ZipCrypto
94
- zf.extract_all("out/")
95
- zf.add("upload.bin", StringIO.new(bytes)) # any IO, streamed on commit
96
- end
97
81
  ```
98
82
 
83
+ Streaming, passwords, limits and the rest are in the cookbook below.
84
+
99
85
  ## Cookbook
100
86
 
101
87
  Zip a directory, unzip into one:
@@ -109,7 +95,8 @@ Ziperu::File.open("site.zip") do |zf|
109
95
  end
110
96
  ```
111
97
 
112
- Build an archive in memory and hand it out, or take one in:
98
+ Build an archive in memory and hand it out, write one straight to an IO,
99
+ or take one in:
113
100
 
114
101
  ```ruby
115
102
  bytes = Ziperu::OutputStream.write_buffer do |zos|
@@ -117,26 +104,45 @@ bytes = Ziperu::OutputStream.write_buffer do |zos|
117
104
  zos.write(csv)
118
105
  end.string
119
106
 
107
+ Ziperu::OutputStream.write_buffer(socket) do |zos| # a pipe or socket is streamed,
108
+ zos.put_next_entry("report.csv") # nothing buffered to the end
109
+ zos.write(csv)
110
+ end
111
+
120
112
  Ziperu::File.open_buffer(params[:upload].read) do |zf|
121
113
  zf.each { |e| puts "#{e.name}: #{e.size} bytes" }
122
114
  end
123
115
  ```
124
116
 
125
- Stream a zip download without a temp file (Rack; in Rails, write to
126
- `response.stream` inside `ActionController::Live` the same way):
117
+ Stream a zip download without a temp file. `OutputStream.body` returns a
118
+ Rack body: an Enumerator of the archive's bytes, produced as the server
119
+ consumes them.
127
120
 
128
121
  ```ruby
122
+ require "ziperu/rails_streaming"
123
+
129
124
  body = Ziperu::OutputStream.body do |zos|
130
125
  attachments.each do |att|
131
126
  zos.put_next_entry(att.filename)
132
127
  att.download { |chunk| zos.write(chunk) }
133
128
  end
134
129
  end
135
- [200, Ziperu::RailsStreaming.headers("attachments.zip"), body] # require "ziperu/rails_streaming"
130
+ [200, Ziperu::RailsStreaming.headers("attachments.zip"), body]
131
+ ```
136
132
 
137
- class ExportsController < ApplicationController # in Rails: headers, body, no Live
133
+ In a Rails controller, `zip_stream` sets the headers and the body, with
134
+ no need for `ActionController::Live`:
135
+
136
+ ```ruby
137
+ class ExportsController < ApplicationController
138
138
  include Ziperu::RailsStreaming
139
- def show = zip_stream("export.zip") { |zos| zos.put_next_entry("a.csv"); zos.write(csv) }
139
+
140
+ def show
141
+ zip_stream("export.zip") do |zos|
142
+ zos.put_next_entry("a.csv")
143
+ zos.write(csv)
144
+ end
145
+ end
140
146
  end
141
147
  ```
142
148
 
@@ -147,6 +153,7 @@ changed archive elsewhere:
147
153
  ```ruby
148
154
  Ziperu::File.open("backup.zip") do |zf|
149
155
  zf.add("logs/today.log", "/var/log/app/today.log")
156
+ zf.add("upload.bin", StringIO.new(bytes)) # any IO, streamed on commit
150
157
  zf.get_output_stream("manifest.json") { |io| io.write(manifest.to_json) }
151
158
  end
152
159
 
@@ -154,7 +161,9 @@ Ziperu::File.open("backup.zip", write: "backup-2.zip") { |zf| zf.remove("old.log
154
161
  Ziperu::File.open("backup.zip", write: false) { |zf| zf.read("manifest.json") } # read-only
155
162
  ```
156
163
 
157
- Pick one entry out of a large archive, or read it all as a stream:
164
+ Pick one entry out of a large archive, or read it all as a stream.
165
+ `foreach` yields one entry at a time in constant memory, however many
166
+ there are:
158
167
 
159
168
  ```ruby
160
169
  entry = Ziperu::File.foreach("huge.zip").find { |e| e.name.end_with?(".sig") }
@@ -264,6 +273,41 @@ Ziperu::File.open(upload) do |zip|
264
273
  end
265
274
  ```
266
275
 
276
+ Unpack whatever was uploaded, a zip or a tar archive, compressed or not.
277
+ `Ziperu.extract` tells which from the first bytes. A tar archive is read
278
+ front to back, so it can come from a pipe or a response body:
279
+
280
+ ```ruby
281
+ Ziperu.extract(upload, "out", **Ziperu::Limits::UPLOAD)
282
+
283
+ Ziperu::Tar.extract_all("release.tar.gz", "src", strip_components: 1)
284
+
285
+ Ziperu::Tar.foreach("logs.tar.zst") do |entry| # one entry at a time
286
+ process(entry.name, entry.read) if entry.file?
287
+ end
288
+ ```
289
+
290
+ Tar extraction follows the rules zip extraction does, and adds its own
291
+ for hard links and devices; [docs/tar.md](docs/tar.md) has them, and
292
+ what is read.
293
+
294
+ Write a tar archive, to a file or to anything with `write`. The
295
+ compression follows the file's name, or `compression:`:
296
+
297
+ ```ruby
298
+ Ziperu::Tar.add_recursive("site.tar.gz", "public")
299
+
300
+ Ziperu::Tar.create("backup.tar.zst", level: 10) do |tar|
301
+ tar.add("report.pdf", "tmp/report.pdf") # a file from disk
302
+ tar.add("upload.bin", StringIO.new(bytes)) # any IO
303
+ tar.add_data("manifest.json", manifest.to_json)
304
+ tar.add_recursive("var/log/app", prefix: "logs/")
305
+ end
306
+
307
+ [200, { "content-type" => "application/gzip" },
308
+ Ziperu::Tar.body(compression: :gzip) { |tar| tar.add_data("report.csv", csv) }]
309
+ ```
310
+
267
311
  ## Migrating from rubyzip
268
312
 
269
313
  Change the Gemfile line and keep `require "zip"`: the `Zip` constant and
@@ -300,14 +344,6 @@ flagged UTF-8 come back as UTF-8 strings; duplicate names in one
300
344
  methods), is in [docs/migrating.md](docs/migrating.md). What rubyzip's own
301
345
  test suite makes of ziperu is in [COMPAT.md](COMPAT.md).
302
346
 
303
- ## Why
304
-
305
- rubyzip is pure Ruby and does per-entry work in Ruby objects. ziperu
306
- parses the central directory once in Rust and hands Ruby a flat metadata
307
- dump, reads entries in large chunks, copies unchanged entries byte for
308
- byte on `commit`, and releases the GVL while inflating from a file or
309
- String buffer and while deflating to a file, so other Ruby threads keep running.
310
-
311
347
  ## Platforms
312
348
 
313
349
  - **Ruby 3.3 to 4.0** are supported and tested on Linux, macOS and Windows.
@@ -324,6 +360,7 @@ bundle install
324
360
  bundle exec rake compile test # build the extension, run the suite
325
361
  bundle exec rake compat # rubyzip's own test suite against ziperu
326
362
  bundle exec rake fuzz # differential fuzzing (TIME=180 for three minutes)
363
+ bundle exec rake fuzz:tar # the same for tar, against Python's tarfile
327
364
  bundle exec rake bench # the table above
328
365
  ```
329
366
 
@@ -337,6 +374,10 @@ run, the release pipeline and the code layout are described in
337
374
  - [Changelog](CHANGELOG.md)
338
375
  - [Migrating from rubyzip](docs/migrating.md): every deliberate difference, and what ziperu adds
339
376
  - [rubyzip compatibility report](COMPAT.md)
377
+ - [Tar archives](docs/tar.md): what is read and written, how extraction behaves, the limits
378
+ - [Benchmarks](docs/benchmarks.md): all three platforms, and which calls release the GVL
379
+ - [Security](SECURITY.md): what extraction and reading guard against
380
+ - [Development](docs/development.md): building, the fuzzer, the release pipeline
340
381
 
341
382
  ## Contributing
342
383
 
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -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)