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.
@@ -0,0 +1,399 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ziperu # rubocop:disable Style/Documentation -- documented in ziperu.rb
4
+ module Tar # rubocop:disable Style/Documentation -- documented in tar.rb
5
+ # Extracts every entry of the tar archive at `path_or_io` (a path, or
6
+ # an IO with `read`, which may be a pipe) into `destination_directory`:
7
+ #
8
+ # Ziperu::Tar.extract_all(upload, 'out', **Ziperu::Limits::UPLOAD)
9
+ # Ziperu::Tar.extract_all('release.tar.gz', 'src', strip_components: 1)
10
+ #
11
+ # The rules are the ones a zip is extracted by. An entry whose name
12
+ # resolves outside the destination is skipped with a warning, and
13
+ # nothing is written through a link already on disk. Times and
14
+ # permission bits are restored (never setuid or setgid); owners are
15
+ # not.
16
+ #
17
+ # - `symlinks:` is `:skip` (the default, with a warning per link) or
18
+ # `:create`, which creates the links whose target stays inside the
19
+ # destination.
20
+ # - A hard link is created when its target is a file this extraction
21
+ # wrote; any other is skipped with a warning.
22
+ # - Devices and fifos are skipped with a warning.
23
+ # - `on_exists:` is `:raise` (the default), `:overwrite` or `:skip`
24
+ # for a path taken before the extraction began. Within one archive
25
+ # the last entry of a name wins, as `tar` has it.
26
+ # - `exclude:` lists globs or Regexps of entry names to leave out.
27
+ # - `strip_components: n` drops the first `n` directories of every
28
+ # name (`tar --strip-components`); entries with no more than that
29
+ # are left out.
30
+ # - `sanitize: :windows` rewrites names Windows refuses.
31
+ # - `progress:` is called with `(entry, done, nil)` after each entry;
32
+ # a tar archive does not say how many it holds.
33
+ #
34
+ # The other keywords are the limit settings, as for `foreach`.
35
+ # Links are created last, after every file. Not in rubyzip.
36
+ def self.extract_all(path_or_io, destination_directory = '.', symlinks: :skip, on_exists: nil, exclude: nil,
37
+ sanitize: nil, strip_components: 0, progress: nil, **limits)
38
+ Reader.open(path_or_io, **limits) do |reader|
39
+ Extraction.new(reader, destination_directory, symlinks: symlinks, on_exists: on_exists, exclude: exclude,
40
+ sanitize: sanitize, strip_components: strip_components,
41
+ progress: progress).run
42
+ end
43
+ nil
44
+ end
45
+
46
+ # The first bytes of gzip, zstd and xz data.
47
+ COMPRESSED_MAGIC = ["\x1f\x8b".b, "\x28\xb5\x2f\xfd".b, "\xfd7zXZ\x00".b].freeze # :nodoc:
48
+ BZIP2_MAGIC = /\ABZh[1-9](?:1AY&SY|\x17\x72\x45\x38\x50\x90)/n # :nodoc:
49
+
50
+ # Whether `head`, the first 512 bytes of some input, begins a tar
51
+ # archive: compressed data (which a zip never starts with), a tar
52
+ # header whose checksum holds, or the zeros an empty archive is.
53
+ def self.head?(head) # :nodoc:
54
+ return true if COMPRESSED_MAGIC.any? { |magic| head.start_with?(magic) } || head.match?(BZIP2_MAGIC)
55
+ return false unless head.bytesize == 512
56
+ return true if head.count("\0") == 512
57
+
58
+ stored = head[148, 8][/[0-7]+/]&.to_i(8) or return false
59
+ bytes = head.bytes
60
+ bytes[148, 8] = [32] * 8
61
+ stored == bytes.sum || stored == bytes.sum { |byte| byte > 127 ? byte - 256 : byte }
62
+ end
63
+
64
+ # One run of `Tar.extract_all`.
65
+ class Extraction # :nodoc:
66
+ include LinkSafety
67
+
68
+ SKIPPED_TYPES = {
69
+ character_device: 'a character device',
70
+ block_device: 'a block device',
71
+ fifo: 'a fifo'
72
+ }.freeze
73
+
74
+ def initialize(reader, destination_directory, symlinks:, on_exists:, exclude:, sanitize:, strip_components:,
75
+ progress:)
76
+ raise ArgumentError, "symlinks: takes :skip or :create, not #{symlinks.inspect}" \
77
+ unless %i[skip create].include?(symlinks)
78
+ raise ArgumentError, "sanitize: takes :windows, not #{sanitize.inspect}" \
79
+ unless [nil, false, :windows].include?(sanitize)
80
+ raise ArgumentError, "strip_components: takes a count, not #{strip_components.inspect}" \
81
+ unless strip_components.kind_of?(::Integer) && strip_components >= 0
82
+
83
+ @reader = reader
84
+ @native = reader.native
85
+ @dest = ::File.absolute_path(destination_directory || '.')
86
+ @policy = on_exists || (reader.settings.on_exists_proc ? :overwrite : :raise)
87
+ @code = ::Ziperu::Entry.on_exists_code(@policy)
88
+ @symlinks = symlinks
89
+ @exclude = exclude
90
+ @sanitize = sanitize
91
+ @strip = strip_components
92
+ @progress = progress
93
+ # The files this run wrote, by path: one of them may be replaced
94
+ # by a later entry of the same name, or be a hard link's target.
95
+ @written = {}
96
+ # The links to create once the files are in, by path, so that a
97
+ # later entry of the same name takes a link's place.
98
+ @links = {}
99
+ end
100
+
101
+ def run
102
+ @native.extract_begin(@dest, @code)
103
+ done = 0
104
+ finished = false
105
+ begin
106
+ @reader.each do |entry|
107
+ extract(entry)
108
+ done += 1
109
+ @progress&.call(entry, done, nil)
110
+ end
111
+ create_links
112
+ finished = true
113
+ ensure
114
+ # The directories get their times and modes whatever happened,
115
+ # as far as that goes; a failure here matters only when nothing
116
+ # failed before it.
117
+ begin
118
+ @native.extract_finish
119
+ rescue StandardError
120
+ raise if finished
121
+ end
122
+ end
123
+ end
124
+
125
+ private
126
+
127
+ def extract(entry)
128
+ unless IOExtras.native_text?(entry.name)
129
+ warn "WARNING: skipped '#{entry.name.inspect[1..-2]}': its name is not valid UTF-8."
130
+ return
131
+ end
132
+ return if @exclude && ::Ziperu::File::ExtractionPlan.excluded?(@exclude, entry.name)
133
+
134
+ name = target_for(entry.name) or return
135
+ case entry.type
136
+ when :file, :other then place(entry, name, false)
137
+ when :directory then place(entry, name, true)
138
+ when :hardlink then defer(entry, name)
139
+ when :symlink
140
+ if @symlinks == :create
141
+ defer(entry, name)
142
+ else
143
+ warn "WARNING: skipped symlink '#{entry.name}' during extract_all."
144
+ end
145
+ else
146
+ warn "WARNING: skipped '#{entry.name}': #{SKIPPED_TYPES.fetch(entry.type)} is not extracted."
147
+ end
148
+ end
149
+
150
+ # The path under the destination a name in the archive goes to, or
151
+ # nil when nothing is left of it: the archive's own root (`./`), or
152
+ # a name `strip_components:` uses up.
153
+ def target_for(name)
154
+ parts = name.split('/').reject { |part| part.empty? || part == '.' }
155
+ return nil if parts.size <= @strip
156
+
157
+ name = parts.drop(@strip).join('/')
158
+ @sanitize == :windows ? ::Ziperu::File.sanitize_windows_name(name) : name
159
+ end
160
+
161
+ def path_of(name)
162
+ ::File.absolute_path(::File.join(@dest, name))
163
+ end
164
+
165
+ # What a path is known by: Windows takes names in any case.
166
+ def key_of(path)
167
+ ::Ziperu::RUNNING_ON_WINDOWS ? path.downcase : path
168
+ end
169
+
170
+ def inside?(path)
171
+ path.start_with?(@dest + ::File::SEPARATOR) || @dest == ::File::SEPARATOR
172
+ end
173
+
174
+ def place(entry, name, directory)
175
+ key = key_of(path_of(name))
176
+ mtime = entry.mtime
177
+ mode = entry.mode & ::Ziperu::Entry::SAFE_PERMISSION_BITS
178
+ outcome = @native.extract_entry([name, mtime.to_i, mtime.nsec, mode, directory, @written.key?(key)])
179
+ case outcome
180
+ when ::Array
181
+ warn_left_out(entry, *outcome)
182
+ when ::Integer
183
+ @written[key] = true
184
+ @links.delete(key)
185
+ else
186
+ # A directory stands there now, or the entry was left out.
187
+ if directory
188
+ @links.delete(key)
189
+ @written.delete(key)
190
+ end
191
+ end
192
+ end
193
+
194
+ def warn_left_out(entry, kind, path)
195
+ if kind == :unsafe
196
+ warn "WARNING: skipped extracting '#{entry.name}' to '#{path}' as unsafe."
197
+ else
198
+ warn "WARNING: skipped extracting '#{entry.name}' through the link '#{path}'."
199
+ end
200
+ end
201
+
202
+ def defer(entry, name)
203
+ path = path_of(name)
204
+ key = key_of(path)
205
+ @links.delete(key)
206
+ @links[key] = [entry, path]
207
+ end
208
+
209
+ # Hard links first, so that none is made through a symlink of this
210
+ # archive's.
211
+ def create_links
212
+ hard, soft = @links.partition { |_, (entry, _)| entry.hardlink? }
213
+ hard.each { |key, (entry, path)| create_hardlink(entry, path, key) }
214
+ soft.each { |key, (entry, path)| create_symlink(entry, path, key) }
215
+ end
216
+
217
+ def create_symlink(entry, path, key)
218
+ return if kept?(path, key)
219
+ return unless link_site?(entry, path)
220
+
221
+ target = entry.link_target
222
+ if (why = symlink_refusal(target, path, @dest))
223
+ warn "WARNING: skipped symlink '#{entry.name}' to '#{target}' as #{why}."
224
+ return
225
+ end
226
+ return unless clear_way(path, key)
227
+
228
+ ::File.symlink(target, path)
229
+ rescue NotImplementedError, Errno::EACCES, Errno::EPERM => e
230
+ warn "WARNING: could not create symlink '#{path}': #{e.message}"
231
+ end
232
+
233
+ def create_hardlink(entry, path, key)
234
+ return if kept?(path, key)
235
+
236
+ target_name = target_for(entry.link_target)
237
+ target = target_name && path_of(target_name)
238
+ unless target && @written.key?(key_of(target)) && real_file?(target)
239
+ warn "WARNING: skipped hard link '#{entry.name}' to '#{entry.link_target}': " \
240
+ 'its target is not a file this extraction wrote.'
241
+ return
242
+ end
243
+ return if key_of(target) == key
244
+ return unless link_site?(entry, path) && clear_way(path, key)
245
+
246
+ ::File.link(target, path)
247
+ @written[key] = true
248
+ rescue NotImplementedError, Errno::EACCES, Errno::EPERM, Errno::EXDEV, Errno::EMLINK => e
249
+ warn "WARNING: could not create hard link '#{path}': #{e.message}"
250
+ end
251
+
252
+ # Whether `on_exists: :skip` leaves what is at `path` alone: there
253
+ # is then nothing to say about the link that would have gone there.
254
+ def kept?(path, key)
255
+ @policy == :skip && !@written.key?(key) && inside?(path) &&
256
+ (::File.symlink?(path) || ::File.exist?(path))
257
+ end
258
+
259
+ def real_file?(path)
260
+ !link_on_the_way(@dest, path) && ::File.lstat(path).file?
261
+ rescue SystemCallError
262
+ false
263
+ end
264
+
265
+ # Whether a link may stand at `path`: inside the destination, with
266
+ # no link on disk on the way there.
267
+ def link_site?(entry, path)
268
+ unless inside?(path) && !IOExtras.windows_stream_name?(path.delete_prefix(@dest))
269
+ warn_left_out(entry, :unsafe, path)
270
+ return false
271
+ end
272
+ if (link = link_on_the_way(@dest, path, leaf: false))
273
+ warn_left_out(entry, :link, link)
274
+ return false
275
+ end
276
+ true
277
+ end
278
+
279
+ # Makes the directories down to `path` and removes what stands
280
+ # there, if the policy allows; false when the link is to be left out.
281
+ def clear_way(path, key)
282
+ ::FileUtils.mkdir_p(::File.dirname(path))
283
+ return true unless ::File.symlink?(path) || ::File.exist?(path)
284
+
285
+ unless @written.key?(key)
286
+ return false if @policy == :skip
287
+ raise DestinationExistsError, path if @policy == :raise
288
+ end
289
+ raise DestinationExistsError, path if ::File.directory?(path) && !::File.symlink?(path)
290
+
291
+ ::File.unlink(path)
292
+ @written.delete(key)
293
+ true
294
+ end
295
+ end
296
+ end
297
+
298
+ # Extracts the archive at `path_or_io` into `destination_directory`,
299
+ # whichever kind it is: a zip, or a tar archive (plain, or compressed
300
+ # with gzip, zstd, xz or bzip2). Which is told from its first bytes.
301
+ #
302
+ # Ziperu.extract(upload, 'out', **Ziperu::Limits::UPLOAD)
303
+ #
304
+ # The keywords are those of `Ziperu::File.extract_all` for a zip and of
305
+ # `Ziperu::Tar.extract_all` for a tar archive. `symlinks:`, `on_exists:`,
306
+ # `exclude:`, `sanitize:`, `progress:` and the limits are common to both;
307
+ # one that the archive's kind does not take is an ArgumentError.
308
+ #
309
+ # A zip has to be sought in, so one that comes from a pipe or socket is
310
+ # read into memory first (`max_archive_size:` bounds that); a tar
311
+ # archive never is.
312
+ # Not in rubyzip.
313
+ def self.extract(path_or_io, destination_directory = '.', **options)
314
+ input, head = Tar::Sniffed.of(path_or_io)
315
+ if Tar.head?(head)
316
+ Tar.extract_all(input, destination_directory, **options)
317
+ elsif IOExtras.path_like?(input)
318
+ ::Ziperu::File.extract_all(input, destination_directory, **options)
319
+ else
320
+ how, open_options = options.partition { |name, _| ::Ziperu::File::EXTRACT_ALL_OPTIONS.include?(name) }.map(&:to_h)
321
+ input = input.whole(Settings.take!(open_options.dup).max_archive_size) if input.kind_of?(Tar::Sniffed::Replay)
322
+ ::Ziperu::File.open_buffer(input, write: false, **open_options) do |zip|
323
+ zip.extract_all(destination_directory, **how)
324
+ end
325
+ end
326
+ nil
327
+ end
328
+
329
+ module Tar
330
+ # The first block of an input, and the input to read it all from
331
+ # afterwards.
332
+ module Sniffed # :nodoc:
333
+ HEAD = 512
334
+
335
+ # `[input, head]`: for a path or an IO that can seek, the input as
336
+ # it was; for one that cannot, a reader that gives the head again
337
+ # before the rest.
338
+ def self.of(path_or_io)
339
+ if path_or_io.kind_of?(::Pathname) || !path_or_io.respond_to?(:read)
340
+ [path_or_io, ::File.binread(::File.path(path_or_io), HEAD) || ''.b]
341
+ elsif IOExtras.seekable?(path_or_io)
342
+ start = path_or_io.tell
343
+ head = path_or_io.read(HEAD) || ''.b
344
+ path_or_io.seek(start)
345
+ [path_or_io, head.b]
346
+ else
347
+ head = read_head(path_or_io)
348
+ [Replay.new(head, path_or_io), head]
349
+ end
350
+ end
351
+
352
+ def self.read_head(io)
353
+ head = ''.b
354
+ while head.bytesize < HEAD
355
+ chunk = io.read(HEAD - head.bytesize) or break
356
+ break if chunk.empty?
357
+
358
+ head << chunk
359
+ end
360
+ head
361
+ end
362
+
363
+ # Reads `head`, then what `io` has left.
364
+ class Replay # :nodoc:
365
+ def initialize(head, io)
366
+ @head = head.dup
367
+ @io = io
368
+ end
369
+
370
+ def read(length = nil, buffer = nil)
371
+ chunk =
372
+ if @head.empty?
373
+ @io.read(length)
374
+ elsif length.nil?
375
+ head = @head
376
+ @head = ''.b
377
+ head + (@io.read || '')
378
+ else
379
+ @head.slice!(0, length)
380
+ end
381
+ return chunk if buffer.nil? || chunk.nil?
382
+
383
+ buffer.replace(chunk)
384
+ end
385
+
386
+ # Everything, in memory, as long as it is no more than `limit`
387
+ # bytes (nil for any amount).
388
+ def whole(limit)
389
+ data = ''.b
390
+ while (chunk = read(1 << 20)) && !chunk.empty?
391
+ data << chunk
392
+ raise LimitError.new('an archive size', data.bytesize, limit) if limit && data.bytesize > limit
393
+ end
394
+ ::StringIO.new(data)
395
+ end
396
+ end
397
+ end
398
+ end
399
+ end