ziperu 0.3.0-aarch64-linux-gnu → 0.4.0-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: 9bb2bc36d5a3657cf91c9612aff78d5202d269eaeeddf0971a4c950a9884d190
4
- data.tar.gz: 4b42c08d65560ba711e8c24dfcf3944b1900c53eddd182e71c57c237f61c60b2
3
+ metadata.gz: 4d12c4f163600c9ead3a6d8178ce69ba6da1573169fa822aeae5ac5264d9020a
4
+ data.tar.gz: 752d8809635efc41ecc3ca2866a0e1ac81b237af45bd2cbb806e8cca85ce5281
5
5
  SHA512:
6
- metadata.gz: 21e847bda0181f5b21c3d2b445a9ccdd2ab33045e2b8eccf8111c1583b52b77bbd10944f8e23ca17258f1bc4d97e819119245049da9afb6ce8e4bdb92d9b1b41
7
- data.tar.gz: 54b697003bfa4ab04f013a7d52f9f3a535f5e9a953db2e23aec530dc7bf69713fed52d952129502c0ea7bd85e67b434b64ad19c57a728c905d086eef2b7dd090
6
+ metadata.gz: bcf4068019a51863facc08578e38ba8f251db456c9ff91e2111bd346ec13c004b71421f66ed1b50a270eeb42ee2294e29af4099b2b40a501aa072e01ecf26fb0
7
+ data.tar.gz: 2bc07a490f3df284595e62bf07775fa81e873316907fd6d630803a5dd36cba18e565002b062b938e0eb02b8da0b1cd78ea938aa648e5a978ac3b8c04199c2911
data/CHANGELOG.md CHANGED
@@ -1,5 +1,122 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 (2026-11-21)
4
+
5
+ Added:
6
+
7
+ - `Ziperu::Tar.foreach` and `Ziperu::Tar::Reader` read tar archives:
8
+ plain, or compressed with gzip, zstd, xz or bzip2, told apart by their
9
+ first bytes and not by their name. An archive is read front to back,
10
+ an entry at a time, in constant memory, from a path or from any IO
11
+ with `read` (a pipe, a socket, a response body). An entry gives its
12
+ name, size, type, mode, time (to the nanosecond where the archive has
13
+ it), link target and owner, and its data through `read` and
14
+ `each_chunk`. v7, ustar, GNU and PAX archives are read, long names and
15
+ extended headers included; sparse files and multi-volume archives are
16
+ refused.
17
+ - `Ziperu::Tar.extract_all(path_or_io, dest)` extracts a tar archive
18
+ under the rules a zip is extracted by: a name that resolves outside
19
+ the destination is skipped with a warning, nothing is written through
20
+ a link already on disk, and times and permission bits are restored
21
+ but never setuid, setgid or an owner. Symlinks are skipped unless
22
+ `symlinks: :create`, and then made only when the target stays inside.
23
+ A hard link is made only to a file the same extraction wrote. Devices
24
+ and fifos are skipped. `on_exists:`, `exclude:`, `sanitize:` and
25
+ `progress:` are as for a zip; `strip_components:` drops leading
26
+ directories. Of two entries with one name the last wins, as `tar` has
27
+ it. Links are created after every file.
28
+ - `Ziperu.extract(path_or_io, dest)` extracts a zip or a tar archive,
29
+ told apart by the first bytes, with the options of whichever it is.
30
+ From a pipe a tar archive is streamed; a zip is read into memory
31
+ first, within `max_archive_size`.
32
+ - `Ziperu::Tar.create(path_or_io) { |tar| ... }` writes a tar archive,
33
+ plain or compressed with gzip, zstd, xz or bzip2 (from the file's name,
34
+ or `compression:`, with `level:`). `add` takes a file from disk or any
35
+ IO, `add_data` a String, and there are `mkdir`, `symlink`, `link` and
36
+ `add_recursive`; `Ziperu::Tar.add_recursive(archive, dir)` does a whole
37
+ directory and `Ziperu::Tar.body` gives a Rack body. What is written is
38
+ ustar, with a PAX extended header only for what ustar cannot hold (a
39
+ long or non-ASCII name, a size of 8 GiB or more). It goes to a pipe or
40
+ socket as readily as to a file, and a file is put in place only once
41
+ it is whole. Owners are not recorded, and with `source_date_epoch` the
42
+ same input gives the same bytes.
43
+ - [docs/tar.md](docs/tar.md) describes what is read and written and how
44
+ extraction behaves. CI now exchanges tar archives with GNU tar, bsdtar, Python's
45
+ tarfile and 7-Zip in both directions, and `rake fuzz:tar` fuzzes the
46
+ reader, the extractor and the writer against Python's tarfile.
47
+ - The limits hold for tar as for zip: `max_entries`, `max_entry_size`,
48
+ `max_total_size`, `max_archive_size` for what is read from an IO, and
49
+ `max_compression_ratio`, which is measured over the stream as it is
50
+ read and so stops a compressed bomb a few megabytes in, read or
51
+ skipped.
52
+ - A compressed tar archive is read to the end of its stream, where
53
+ gzip, xz and bzip2 keep their checksum: tar has none for an entry's
54
+ data. A long name or extended header over 1 MiB is refused, and an xz
55
+ stream that asks for more than 256 MiB to decode.
56
+
57
+ Fixed:
58
+
59
+ - On Windows an entry with a colon in its name was written as an
60
+ alternate data stream: `a.txt:x` went into `a.txt`, a file that could
61
+ have been in the destination before and was neither replaced nor
62
+ reported, whatever `on_exists:` said. And `C:x`, a path relative to
63
+ the current directory of drive C, was written there: outside the
64
+ destination. Such an entry is now skipped with a warning, as one that resolves outside the destination is;
65
+ `sanitize: :windows` rewrites the name and extracts it. This was true
66
+ of zip extraction in every release so far.
67
+
68
+ Internal:
69
+
70
+ - The native extractor is in two parts: `placer.rs` decides where an
71
+ entry goes and what is refused on the way (the path check, links on
72
+ disk, what is already there), and `extract.rs` reads zip entries into
73
+ the files it opens. Nothing changes in what is extracted or how.
74
+ - The memory growth check failed a nightly run on code that had passed
75
+ the day before. It sampled resident memory after a full GC, but memory
76
+ glibc had freed and not yet returned swung the samples between 68 and
77
+ 107 MiB. It now calls `malloc_trim` before each sample: the workload
78
+ then sits at 23.8 MiB for all 600 iterations, and the growth allowed
79
+ drops from 8 MiB to 3.
80
+
81
+ ## 0.3.1 (2026-11-16)
82
+
83
+ Fixed:
84
+
85
+ - An entry that `File.foreach` yielded from a path could not be read once
86
+ `foreach` had returned: `get_input_stream` raised `IOError: closed
87
+ archive`. That covered `foreach(path).find { ... }` and entries
88
+ collected in the block. rubyzip allows it, and so does an entry of a
89
+ closed `Ziperu::File`; the archive is now reopened for these entries
90
+ too. Found by write_xlsx's test suite, 974 of whose tests failed on it.
91
+ - `File#extract`, and `extract_all` with a block, left an empty file
92
+ behind when the entry could not be read (a bad CRC, a wrong password).
93
+ The file is removed, as the native path of `extract_all` already did.
94
+ - `File#read` and `extract_all` raised a plain `Zip::Error` for an entry
95
+ in a compression method that cannot be read. They raise
96
+ `Zip::CompressionMethodError`, as rubyzip does and as
97
+ `get_input_stream` did, so one `rescue` covers every way of reading.
98
+ - `File.extract_all(path, dest, password: "...")` raised "unknown
99
+ keyword": the one-liner passed every option to `#extract_all` and none
100
+ to `open`. It now takes both kinds, the limits included.
101
+ - `File.foreach` takes `password:`, and the entries it yields are read
102
+ with it. They could only be read by building a decrypter for each.
103
+ - A `metadata_encoding:` Ruby does not know raises `ArgumentError`. It was
104
+ ignored, and names stayed binary with nothing to say why.
105
+ - The message for an archive cut short named Rust types ("Unexpected end
106
+ of zip::format::blocks::Zip32CDEBlock"). It says what is cut short: the
107
+ end of central directory record, a central directory entry and so on.
108
+ - `File#inspect` is one line (the path, the entry count, read-only or
109
+ uncommitted). The default listed every entry: half a megabyte for an
110
+ archive of 5,000, in irb, a log line or an error message.
111
+ - `InputStream.new(path, offset: n)` closes the archive before raising
112
+ when no entry starts at `n`. It was left for the GC.
113
+
114
+ Internal:
115
+
116
+ - The weekly run of other gems' test suites never got as far as running
117
+ one: installing the built gem with `--local` could not find `rb_sys`,
118
+ and the script had lost its execute bit.
119
+
3
120
  ## 0.3.0 (2026-11-14)
4
121
 
5
122
  Security:
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
@@ -52,6 +52,11 @@ module Ziperu
52
52
  stored&.native(offset)
53
53
  end
54
54
 
55
+ # The password its owner was given for the archive, or nil.
56
+ def password
57
+ nil
58
+ end
59
+
55
60
  # The record's local-header extra fields, as stored.
56
61
  def local_extra(offset)
57
62
  stored.local_extra(offset)
@@ -69,8 +74,9 @@ module Ziperu
69
74
 
70
75
  NONE = None.new.freeze
71
76
 
72
- # A record of `native`, the archive `owner` (a Ziperu::File, or nil
73
- # for an entry read through an InputStream) has open. `index` is nil
77
+ # A record of `native`, the archive `owner` has open: a Ziperu::File,
78
+ # a Reopener for an entry `File.foreach` yielded from a path, or nil
79
+ # for an entry read through an InputStream. `index` is nil
74
80
  # for a record the native core cannot address by index (one of
75
81
  # several under the same name), which is found by its offset.
76
82
  class Archive
@@ -89,11 +95,14 @@ module Ziperu
89
95
  self
90
96
  end
91
97
 
92
- # The native archive, reopened if the owning Ziperu::File released
93
- # it on close: rubyzip lets entries be read after `close`.
98
+ def password
99
+ @owner.password if @owner.respond_to?(:password)
100
+ end
101
+
102
+ # The native archive, reopened if its owner released it on close:
103
+ # rubyzip lets entries be read after `close`.
94
104
  def native(offset)
95
- if @native.closed? && @owner.kind_of?(::Ziperu::File)
96
- reopened = @owner.native_archive
105
+ if @native.closed? && (reopened = (@owner.native_archive if @owner.respond_to?(:native_archive)))
97
106
  unless still_at_place?(reopened, offset)
98
107
  where = @index ? "at index #{@index} of" : 'in'
99
108
  raise EntryMovedError, "entry '#{@raw_name}' is no longer #{where} #{@owner.name}"
@@ -132,6 +141,32 @@ module Ziperu
132
141
  end
133
142
  end
134
143
 
144
+ # Stands in for a Ziperu::File as the owner of the entries that
145
+ # `File.foreach` yields: it has the password given for the archive,
146
+ # and for an archive at a path it reopens it, so the entries can be
147
+ # read once the walk is over (`foreach(path).find { ... }`, or
148
+ # entries collected in the block). One is shared by all the entries
149
+ # of a walk, and so is the archive it reopens.
150
+ class Reopener
151
+ attr_reader :name, :password
152
+
153
+ # `name` is the archive's path, or nil for one read from an IO,
154
+ # which cannot be opened again.
155
+ def initialize(name, settings, password = nil)
156
+ @name = name
157
+ @settings = settings
158
+ @password = password
159
+ @native = nil
160
+ end
161
+
162
+ def native_archive
163
+ return if @name.nil?
164
+
165
+ @native = InputStream.open_archive(@name, @settings) if @native.nil? || @native.closed?
166
+ @native
167
+ end
168
+ end
169
+
135
170
  # Data still outside the archive.
136
171
  class Pending
137
172
  include Defaults
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
@@ -266,12 +267,22 @@ module Ziperu
266
267
  fstype version_made_by dos_date dos_time comment extra header_offset].freeze # :nodoc:
267
268
 
268
269
  # Build an entry from one row (see ROW_FIELDS).
269
- def self.from_row(archive, row, zipfile = nil, metadata_encoding: nil, settings: ::Ziperu) # :nodoc:
270
+ # `owner` is who reopens the archive for the entry once it is closed:
271
+ # `zipfile`, unless another is given (see Source::Reopener).
272
+ def self.from_row(archive, row, zipfile = nil, metadata_encoding: nil, settings: ::Ziperu, owner: zipfile) # :nodoc:
270
273
  entry = allocate
271
- entry.send(:init_from_row, archive, row, zipfile, metadata_encoding, settings)
274
+ entry.send(:init_from_row, archive, row, zipfile, metadata_encoding, settings, owner)
272
275
  entry
273
276
  end
274
277
 
278
+ # Raises for a `metadata_encoding:` Ruby does not know, which was once
279
+ # ignored: names then stayed binary and nothing said why.
280
+ def self.check_metadata_encoding!(encoding) # :nodoc:
281
+ ::Encoding.find(encoding) unless encoding.nil?
282
+ rescue ::ArgumentError
283
+ raise ::ArgumentError, "unknown metadata_encoding: #{encoding.inspect}"
284
+ end
285
+
275
286
  # Is this entry encrypted?
276
287
  def encrypted?
277
288
  gp_flags.anybits?(ENCRYPTED_GPFLAG)
@@ -497,7 +508,8 @@ module Ziperu
497
508
  dest_dir = ::File.absolute_path(destination_directory || '.')
498
509
  extract_path = ::File.absolute_path(::File.join(dest_dir, entry_path))
499
510
 
500
- unless extract_path.start_with?(dest_dir + ::File::SEPARATOR) || dest_dir == ::File::SEPARATOR
511
+ inside = extract_path.start_with?(dest_dir + ::File::SEPARATOR) || dest_dir == ::File::SEPARATOR
512
+ unless inside && !IOExtras.windows_stream_name?(entry_path)
501
513
  warn "WARNING: skipped extracting '#{@name}' to '#{extract_path}' as unsafe."
502
514
  return self
503
515
  end
@@ -597,9 +609,13 @@ module Ziperu
597
609
  end
598
610
 
599
611
  # The decrypter for this entry when the owning `Ziperu::File` was
600
- # opened with a password; nil otherwise, or for a plain entry.
612
+ # opened with a password, or `File.foreach` was given one; nil
613
+ # otherwise, or for a plain entry.
601
614
  def default_decrypter # :nodoc:
602
- return unless encrypted? && @zipfile.kind_of?(::Ziperu::File) && (pw = @zipfile.password)
615
+ return unless encrypted?
616
+
617
+ pw = @zipfile.kind_of?(::Ziperu::File) ? @zipfile.password : @source.password
618
+ return unless pw
603
619
 
604
620
  aes? ? AESDecrypter.new(pw) : TraditionalDecrypter.new(pw)
605
621
  end
@@ -839,7 +855,8 @@ module Ziperu
839
855
  # one: in a single native call when the entry is in an archive and its
840
856
  # declared size is to be trusted, through a stream otherwise.
841
857
  def read_all # :nodoc:
842
- if !pending_data? && @source.stored? && !encrypted? && @settings.validate_entry_sizes
858
+ if !pending_data? && @source.stored? && !encrypted? && @settings.validate_entry_sizes &&
859
+ READABLE_COMPRESSION_METHODS.include?(compression_method)
843
860
  get_raw_input_string
844
861
  else
845
862
  get_input_stream(&:read)
@@ -911,7 +928,15 @@ module Ziperu
911
928
  ::FileUtils.rm_f(staged) unless done
912
929
  end
913
930
  else
914
- ::File.open(dest_path, WRITE_NO_FOLLOW, binmode: true) { |os| write_data_to(os) }
931
+ # Nothing was there, so an extraction that fails takes away what
932
+ # it had written rather than leave a file cut short.
933
+ done = false
934
+ begin
935
+ ::File.open(dest_path, WRITE_NO_FOLLOW, binmode: true) { |os| write_data_to(os) }
936
+ done = true
937
+ ensure
938
+ ::FileUtils.rm_f(dest_path) unless done
939
+ end
915
940
  end
916
941
 
917
942
  set_extra_attributes_on_path(dest_path)
@@ -985,43 +1010,6 @@ module Ziperu
985
1010
  warn "WARNING: could not create symlink '#{dest_path}': #{e.message}"
986
1011
  end
987
1012
 
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
-
1025
1013
  def set_unix_attributes_on_path(dest_path) # :nodoc:
1026
1014
  # Ignore setuid/setgid bits by default. Honour if @restore_ownership.
1027
1015
  unix_perms_mask = @restore_ownership ? PERMISSION_BITS : SAFE_PERMISSION_BITS
@@ -1064,7 +1052,7 @@ module Ziperu
1064
1052
  raise EntryNameError if name.length > MAX_FIELD_LENGTH
1065
1053
  end
1066
1054
 
1067
- def init_from_row(archive, row, zipfile, metadata_encoding, settings)
1055
+ def init_from_row(archive, row, zipfile, metadata_encoding, settings, owner)
1068
1056
  index, name, size, compressed_size, crc, method, flags, external_attributes, fstype, _version,
1069
1057
  dos_date, dos_time, comment, extra, header_offset = row
1070
1058
  @settings = settings
@@ -1080,7 +1068,7 @@ module Ziperu
1080
1068
  # the archive knows the entry by.
1081
1069
  @gp_flags = flags
1082
1070
  @original_name = name
1083
- @source = archive ? Source::Archive.new(archive, zipfile, index, @original_name) : Source::NONE
1071
+ @source = archive ? Source::Archive.new(archive, owner, index, @original_name) : Source::NONE
1084
1072
  # Most entries have no comment and many no extra fields: those share
1085
1073
  # one empty String rather than carrying their own.
1086
1074
  @extra = nil
@@ -44,6 +44,8 @@ module Ziperu
44
44
  # itself (`unzip -j`); `sanitize: :windows` rewrites names that Windows
45
45
  # refuses (`<>:"|?*`, control characters, a trailing dot or space,
46
46
  # `CON`, `NUL` and the like) so the archive extracts there at all.
47
+ EXTRACT_ALL_OPTIONS = %i[symlinks progress threads on_exists exclude junk_paths sanitize].freeze # :nodoc:
48
+
47
49
  def extract_all(destination_directory = '.', symlinks: :skip, progress: nil, threads: 1,
48
50
  on_exists: nil, exclude: nil, junk_paths: false, sanitize: nil, &block)
49
51
  targets = ExtractionPlan.new(@cdir.writable_entries, exclude: exclude, junk_paths: junk_paths,
@@ -118,6 +120,16 @@ module Ziperu
118
120
  end
119
121
  end
120
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
+
121
133
  # `entries` are the archive's writable entries (of several records
122
134
  # under one name only the last, the one rubyzip would know).
123
135
  def initialize(entries, exclude: nil, junk_paths: false, sanitize: nil)
@@ -188,12 +200,7 @@ module Ziperu
188
200
  # (`File.fnmatch` with `*` crossing `/`, as `unzip -x` has it) or a
189
201
  # Regexp.
190
202
  def excluded?(name)
191
- Array(@exclude).any? do |pattern|
192
- case pattern
193
- when ::Regexp then pattern.match?(name)
194
- else ::File.fnmatch?(pattern.to_s, name, ::File::FNM_EXTGLOB | ::File::FNM_DOTMATCH)
195
- end
196
- end
203
+ self.class.excluded?(@exclude, name)
197
204
  end
198
205
 
199
206
  # The path under the destination an entry goes to.
@@ -262,6 +269,9 @@ module Ziperu
262
269
  return false unless entry.instance_of?(::Ziperu::Entry) && entry.index && entry.backed_by?(native)
263
270
  # An encrypted entry goes through the Ruby path, which has the password.
264
271
  return false if entry.encrypted?
272
+ # So does one in a method that cannot be read, for the error rubyzip
273
+ # raises (CompressionMethodError).
274
+ return false unless READABLE_COMPRESSION_METHODS.include?(entry.compression_method)
265
275
  return false unless entry.file? || entry.directory?
266
276
 
267
277
  IOExtras.native_text?(entry.name)