ziperu 0.2.3-x86_64-linux-gnu → 0.3.0-x86_64-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +151 -0
  3. data/README.md +35 -7
  4. data/lib/zip.rb +3 -3
  5. data/lib/ziperu/3.1/ziperu.so +0 -0
  6. data/lib/ziperu/3.2/ziperu.so +0 -0
  7. data/lib/ziperu/3.3/ziperu.so +0 -0
  8. data/lib/ziperu/3.4/ziperu.so +0 -0
  9. data/lib/ziperu/4.0/ziperu.so +0 -0
  10. data/lib/ziperu/central_directory.rb +4 -8
  11. data/lib/ziperu/constants.rb +8 -0
  12. data/lib/ziperu/crypto.rb +10 -2
  13. data/lib/ziperu/dos_time.rb +1 -1
  14. data/lib/ziperu/entry.rb +226 -109
  15. data/lib/ziperu/entry_set.rb +0 -5
  16. data/lib/ziperu/errors.rb +4 -2
  17. data/lib/ziperu/extra_field/zip64.rb +1 -3
  18. data/lib/ziperu/extra_field.rb +10 -10
  19. data/lib/ziperu/file/commit.rb +255 -0
  20. data/lib/ziperu/file/extraction.rb +280 -0
  21. data/lib/ziperu/file.rb +51 -398
  22. data/lib/ziperu/file_split.rb +1 -3
  23. data/lib/ziperu/filesystem/dir.rb +3 -9
  24. data/lib/ziperu/filesystem/file.rb +2 -6
  25. data/lib/ziperu/filesystem/zip_file_name_mapper.rb +2 -2
  26. data/lib/ziperu/input_stream.rb +28 -32
  27. data/lib/ziperu/ioextras/abstract_input_stream.rb +83 -31
  28. data/lib/ziperu/ioextras/abstract_output_stream.rb +1 -3
  29. data/lib/ziperu/ioextras/fake_io.rb +1 -3
  30. data/lib/ziperu/ioextras.rb +6 -0
  31. data/lib/ziperu/limits.rb +48 -0
  32. data/lib/ziperu/null_input_stream.rb +1 -1
  33. data/lib/ziperu/output_stream.rb +118 -31
  34. data/lib/ziperu/pass_thru_decompressor.rb +1 -3
  35. data/lib/ziperu/rails_streaming.rb +5 -5
  36. data/lib/ziperu/remote_io.rb +181 -32
  37. data/lib/ziperu/size_estimator.rb +27 -19
  38. data/lib/ziperu/verify_report.rb +62 -0
  39. data/lib/ziperu/version.rb +2 -2
  40. data/lib/ziperu.rb +19 -17
  41. metadata +7 -2
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Ziperu
4
- # Writes zip archives entry by entry, with rubyzip's `Ziperu::OutputStream`
4
+ # Writes zip archives entry by entry, with rubyzip's `Zip::OutputStream`
5
5
  # API: `put_next_entry` opens an entry, then the IO-like methods (`<<`,
6
6
  # `write`, `puts`, `print`) fill it.
7
7
  #
@@ -53,6 +53,7 @@ module Ziperu
53
53
  # stay as they are and the new ones follow them. Its comment is
54
54
  # kept unless `comment=` is called.
55
55
  raise ArgumentError, 'append: takes a path, not an IO' if stream
56
+
56
57
  @writer = Native::Writer.open_append(file_name.to_s)
57
58
  elsif stream
58
59
  @io = file_name
@@ -80,6 +81,7 @@ module Ziperu
80
81
  # An append keeps the archive's own comment unless one is set.
81
82
  @keep_comment = append
82
83
  @closed = false
84
+ @aborted = false
83
85
  @current_entry = nil
84
86
  @written = []
85
87
  # On a stream, a file entry is begun in the native writer only when
@@ -145,7 +147,7 @@ module Ziperu
145
147
  # as with #open and #write_buffer.
146
148
  # Not in rubyzip.
147
149
  def body(**opts, &block)
148
- raise ArgumentError, "a block that writes the entries is required" unless block
150
+ raise ArgumentError, 'a block that writes the entries is required' unless block
149
151
 
150
152
  Enumerator.new { |yielder| write_buffer(Yielder.new(yielder), **opts, &block) }
151
153
  end
@@ -170,7 +172,7 @@ module Ziperu
170
172
  return if @closed
171
173
 
172
174
  finish_archive
173
- @io.close if @io && @io.respond_to?(:close)
175
+ @io.close if @io.respond_to?(:close)
174
176
  @closed = true
175
177
  nil
176
178
  end
@@ -184,6 +186,7 @@ module Ziperu
184
186
  # does.
185
187
  def abort # :nodoc:
186
188
  @aborted = true
189
+ discard_writes
187
190
  if @append || @io
188
191
  @writer.abort
189
192
  @closed = true
@@ -255,6 +258,7 @@ module Ziperu
255
258
  entry = @current_entry
256
259
  raise Error, 'there is no entry being written to take back' if entry.nil? || !@written.last.equal?(entry)
257
260
 
261
+ discard_writes
258
262
  if @deferred
259
263
  @deferred = nil
260
264
  else
@@ -304,10 +308,11 @@ module Ziperu
304
308
  # take it (seekable sink, no encryption).
305
309
  def put_entries(entries, threads: 1) # :nodoc:
306
310
  parallel = threads > 1 && !@streamed && @encrypter.kind_of?(NullEncrypter)
307
- entries.chunk { |e| parallel && e.write_plan == :restream && e.file? && !e.filepath.nil? }
308
- .each do |from_disk, run|
309
- if from_disk && run.size > 1
311
+ entries.chunk { |e| put_kind(e, parallel) }.each do |kind, run|
312
+ if kind == :from_disk && run.size > 1
310
313
  add_from_disk_parallel(run, threads)
314
+ elsif kind.kind_of?(Native::Archive) && run.size > 1
315
+ copy_raw_entries(kind, run)
311
316
  else
312
317
  run.each { |e| e.write_to_zip_output_stream(self) }
313
318
  end
@@ -315,6 +320,48 @@ module Ziperu
315
320
  nil
316
321
  end
317
322
 
323
+ # How `put_entries` writes `entry`: :from_disk (compressed on the
324
+ # pool), the native archive it is copied raw from as it is (runs of
325
+ # those go in one call), or :one (by itself).
326
+ def put_kind(entry, parallel)
327
+ return :from_disk if parallel && entry.write_plan == :restream && entry.file? && !entry.filepath.nil?
328
+ return entry.archive if entry.plain_raw_copy?
329
+
330
+ :one
331
+ end
332
+ private :put_kind
333
+
334
+ # Copies `entries`, all of `archive` and each as it is, in one call to
335
+ # the native writer.
336
+ def copy_raw_entries(archive, entries)
337
+ check_open!
338
+ start_deferred
339
+ flush_writes
340
+ if @stream_names
341
+ entries.each do |e|
342
+ name = e.name.b
343
+ raise EntryExistsError.new('put_next_entry', e.name) if @stream_names.key?(name)
344
+
345
+ @stream_names[name] = true
346
+ end
347
+ end
348
+ @writer.raw_copy_many(archive, entries.map(&:index))
349
+ @written.concat(entries)
350
+ @current_entry = nil
351
+ rescue Native::DuplicateEntryError
352
+ raise_duplicate_among(entries)
353
+ end
354
+ private :copy_raw_entries
355
+
356
+ # The native core refused a name already in the archive without saying
357
+ # which; the names written so far and those of `entries` tell.
358
+ def raise_duplicate_among(entries)
359
+ names = @written.map(&:name) + entries.map(&:name)
360
+ name = names.tally.find { |_, count| count > 1 }&.first || entries.first.name
361
+ raise EntryExistsError.new('put_next_entry', name)
362
+ end
363
+ private :raise_duplicate_among
364
+
318
365
  # A batch is compressed to memory in full before it is appended, so
319
366
  # the batches are bounded by the bytes they read.
320
367
  PARALLEL_BATCH_BYTES = 256 * 1024 * 1024 # :nodoc:
@@ -325,6 +372,7 @@ module Ziperu
325
372
  bytes = 0
326
373
  flush = lambda do
327
374
  items = batch.map { |e| [e.name.b, e.filepath.to_s, native_entry_options(e)] }
375
+ flush_writes
328
376
  @writer.add_files_parallel(items, threads)
329
377
  @written.concat(batch)
330
378
  batch = []
@@ -338,10 +386,7 @@ module Ziperu
338
386
  flush.call unless batch.empty?
339
387
  @current_entry = nil
340
388
  rescue Native::DuplicateEntryError
341
- # The native core does not say which; the names tell.
342
- names = @written.map(&:name) + entries.map(&:name)
343
- name = names.tally.find { |_, count| count > 1 }&.first || entries.first.name
344
- raise EntryExistsError.new('put_next_entry', name)
389
+ raise_duplicate_among(entries)
345
390
  end
346
391
  private :add_from_disk_parallel
347
392
 
@@ -363,6 +408,7 @@ module Ziperu
363
408
  unix_perms: entry.unix_perms }
364
409
  end
365
410
  start_deferred
411
+ flush_writes
366
412
  @stream_names[(new_name || entry.name).to_s.b] = true if @stream_names
367
413
  @writer.raw_copy(entry.archive, entry.index, new_name, touch_opts)
368
414
  @written << entry
@@ -377,22 +423,40 @@ module Ziperu
377
423
  def copy_encrypted_entry(entry, new_name = nil) # :nodoc:
378
424
  check_copyable!(entry)
379
425
  opts = native_entry_options(entry).merge(
380
- zipcrypto: true, descriptor: entry.gp_flags & 8 != 0 # bit 3: data descriptor follows
426
+ zipcrypto: true, descriptor: entry.gp_flags.anybits?(Entry::DATA_DESCRIPTOR_GPFLAG)
381
427
  )
428
+ start_deferred
429
+ flush_writes
382
430
  @writer.copy_zipcrypto(entry.archive, entry.index, (new_name || entry.name).b, opts)
383
431
  @written << entry
384
432
  @current_entry = nil
385
433
  end
386
434
 
435
+ # Writes shorter than this are gathered (see `<<`).
436
+ SMALL_WRITE = 16 * 1024 # :nodoc:
437
+ # Gathered writes go to the native writer once they reach this.
438
+ WRITE_BUFFER = 64 * 1024 # :nodoc:
439
+
387
440
  # Modeled after IO.<<
441
+ #
442
+ # Small writes (`puts` of a line, `<<` of a field) are gathered here
443
+ # and handed to the native writer 64 KB at a time: one call into it
444
+ # costs about what deflating a few KB does. Whatever is gathered goes
445
+ # in before anything else the writer does.
388
446
  def <<(data)
389
447
  raise IOError, 'closed stream' if @closed || @current_entry.nil?
390
- if @current_entry.directory?
391
- raise Error, "cannot write data to directory entry '#{@current_entry.name}'"
392
- end
448
+ raise Error, "cannot write data to directory entry '#{@current_entry.name}'" if @current_entry.directory?
393
449
 
394
450
  start_deferred
395
- @writer.write(data.to_s.b)
451
+ data = data.to_s
452
+ if data.bytesize >= SMALL_WRITE
453
+ flush_writes
454
+ @writer.write(data.b)
455
+ else
456
+ gathered = (@gathered ||= +''.b)
457
+ gathered << (data.encoding == ::Encoding::BINARY || data.ascii_only? ? data : data.b)
458
+ flush_writes if gathered.bytesize >= WRITE_BUFFER
459
+ end
396
460
  self
397
461
  end
398
462
 
@@ -402,22 +466,42 @@ module Ziperu
402
466
  raise IOError, 'closed stream' if @closed || @current_entry.nil?
403
467
 
404
468
  start_deferred
469
+ flush_writes
405
470
  @writer.write_file(path)
406
471
  self
407
472
  end
408
473
 
409
474
  private
410
475
 
476
+ # Hands the gathered small writes (see `<<`) to the native writer.
477
+ def flush_writes
478
+ gathered = @gathered
479
+ return if gathered.nil? || gathered.empty?
480
+
481
+ # Taken first: should the write raise, the bytes are not written
482
+ # again by the next flush.
483
+ @gathered = nil
484
+ @writer.write(gathered)
485
+ end
486
+
487
+ # Drops the gathered small writes, which belong to the entry being
488
+ # taken back or abandoned.
489
+ def discard_writes
490
+ @gathered = nil
491
+ end
492
+
411
493
  def finish_archive
412
494
  unless @keep_comment
413
495
  comment = @comment.to_s.b
414
- if comment.bytesize > 0xFFFF
415
- raise ArgumentError, "archive comment is #{comment.bytesize} bytes; the limit is 65535"
496
+ if comment.bytesize > MAX_FIELD_LENGTH
497
+ raise ArgumentError,
498
+ "archive comment is #{comment.bytesize} bytes; the limit is #{MAX_FIELD_LENGTH}"
416
499
  end
417
500
 
418
501
  @writer.comment = comment
419
502
  end
420
503
  start_deferred
504
+ flush_writes
421
505
  @current_entry = nil
422
506
  begin
423
507
  bytes, stats = @writer.finish
@@ -449,6 +533,7 @@ module Ziperu
449
533
  end
450
534
 
451
535
  start_deferred
536
+ flush_writes
452
537
  opts = native_entry_options(entry)
453
538
  if @stream_names
454
539
  # The native writer would catch a second entry under a name only
@@ -495,7 +580,6 @@ module Ziperu
495
580
 
496
581
  raise Error, "entry '#{entry.name}' shares its name with another record and cannot be copied raw"
497
582
  end
498
- private :check_open!, :check_copyable!
499
583
 
500
584
  # Translate a Ziperu::Entry into the Hash the native writer takes.
501
585
  def native_entry_options(entry)
@@ -513,25 +597,29 @@ module Ziperu
513
597
  # An empty XZ or PPMd entry is a stream with no blocks, which 7-Zip
514
598
  # refuses ("data after the end of the payload"); an empty file is
515
599
  # stored, as Info-ZIP stores every empty file.
516
- method = Entry::STORED if entry.size_known? && entry.size.zero? && [Entry::XZ, Entry::PPMD].include?(method)
600
+ method = Entry::STORED if empty_entry?(entry) && [Entry::XZ, Entry::PPMD].include?(method)
517
601
  {
518
- method: method,
519
- level: (level if method != Entry::STORED && level && level != Zlib::DEFAULT_COMPRESSION),
520
- dos_date: time.to_binary_dos_date,
521
- dos_time: time.to_binary_dos_time,
522
- unix_perms: entry.unix_perms,
523
- fstype: entry.fstype,
524
- large_file: zip64_needed?(entry, zip64_suppressed),
525
- comment: entry.comment.to_s.b,
526
- extra: extra.to_local_bin.b,
602
+ method: method,
603
+ level: (level if method != Entry::STORED && level && level != Zlib::DEFAULT_COMPRESSION),
604
+ dos_date: time.to_binary_dos_date,
605
+ dos_time: time.to_binary_dos_time,
606
+ unix_perms: entry.unix_perms,
607
+ fstype: entry.fstype,
608
+ large_file: zip64_needed?(entry, zip64_suppressed),
609
+ comment: entry.comment.to_s.b,
610
+ extra: extra.to_local_bin.b,
527
611
  central_extra: extra.to_c_dir_bin.b,
528
612
  # The language encoding flag on every entry (`Ziperu.unicode_names`),
529
613
  # which the native writer sets by patching the headers; a non-ASCII
530
614
  # UTF-8 name gets it from the native core regardless.
531
- efs: (entry.gp_flags & Entry::EFS) != 0
615
+ efs: entry.gp_flags.anybits?(Entry::EFS)
532
616
  }
533
617
  end
534
618
 
619
+ def empty_entry?(entry)
620
+ entry.size_known? && entry.size.zero? # rubocop:disable Style/ZeroLengthPredicate -- an Integer
621
+ end
622
+
535
623
  # The fields a new entry gets unless it has them (see
536
624
  # `Ziperu.write_extended_timestamps`). An entry rewritten from an
537
625
  # archive keeps exactly the fields it had.
@@ -542,7 +630,6 @@ module Ziperu
542
630
 
543
631
  extra.create(:universaltime).mtime = DOSTime.from_time(entry.time)
544
632
  end
545
- private :add_default_fields
546
633
 
547
634
  # rubyzip writes a zip64 extra for a file entry only when it has to:
548
635
  # the size is unknown up front (it may turn out huge) or is already
@@ -552,7 +639,7 @@ module Ziperu
552
639
  # `Ziperu.write_zip64_support = :always` makes every file entry
553
640
  # zip64-ready, for testing readers.
554
641
  def zip64_needed?(entry, suppressed)
555
- return true if entry.size >= 0xFFFFFFFF || entry.compressed_size >= 0xFFFFFFFF
642
+ return true if entry.size >= ZIP64_SIZE_LIMIT || entry.compressed_size >= ZIP64_SIZE_LIMIT
556
643
  return false unless entry.file?
557
644
  return entry.zip64 unless entry.zip64.nil?
558
645
  return true if @settings.write_zip64_support == :always && !suppressed
@@ -13,9 +13,7 @@ module Ziperu
13
13
  def read(maxlen = nil)
14
14
  return (maxlen.nil? || maxlen.zero? ? '' : nil) if eof?
15
15
 
16
- if maxlen.nil? || (@read_so_far + maxlen) > decompressed_size
17
- maxlen = decompressed_size - @read_so_far
18
- end
16
+ maxlen = decompressed_size - @read_so_far if maxlen.nil? || (@read_so_far + maxlen) > decompressed_size
19
17
 
20
18
  @read_so_far += maxlen
21
19
  input_stream.read(maxlen)
@@ -45,12 +45,12 @@ module Ziperu
45
45
  # [200, Ziperu::RailsStreaming.headers("export.zip"), Ziperu::OutputStream.body { ... }]
46
46
  def headers(filename, size: nil, type: 'application/zip')
47
47
  h = {
48
- 'content-type' => type,
48
+ 'content-type' => type,
49
49
  'content-disposition' => content_disposition(filename),
50
50
  # Proxies (nginx) and Rack::ETag must not hold the body back.
51
- 'x-accel-buffering' => 'no',
52
- 'cache-control' => 'no-cache',
53
- 'last-modified' => Time.now.httpdate
51
+ 'x-accel-buffering' => 'no',
52
+ 'cache-control' => 'no-cache',
53
+ 'last-modified' => Time.now.httpdate
54
54
  }
55
55
  h['content-length'] = size.to_s if size
56
56
  h
@@ -61,7 +61,7 @@ module Ziperu
61
61
  def content_disposition(filename)
62
62
  name = filename.to_s
63
63
  ascii = name.encode('US-ASCII', undef: :replace, invalid: :replace, replace: '_').delete('"\\')
64
- encoded = name.b.gsub(/[^A-Za-z0-9!#$&+.^_`|~-]/) { |c| format('%%%02X', c.ord) }
64
+ encoded = name.b.gsub(/[^A-Za-z0-9!#{::Regexp.last_match(0)}+.^_`|~-]/) { |c| format('%%%02X', c.ord) }
65
65
  "attachment; filename=\"#{ascii}\"; filename*=UTF-8''#{encoded}"
66
66
  end
67
67
  end
@@ -42,6 +42,12 @@ module Ziperu
42
42
  # directory record, and for most archives the whole central directory.
43
43
  TAIL_SIZE = 64 * 1024
44
44
  MAX_REDIRECTS = 5
45
+ HTTP_SCHEMES = %w[http https].freeze
46
+ DEFAULT_MAX_FULL_DOWNLOAD = 64 * 1024 * 1024
47
+ # How much of an answer that is neither data nor a redirect is read.
48
+ ERROR_BODY_LIMIT = 64 * 1024
49
+ DEFAULT_OPEN_TIMEOUT = 10
50
+ DEFAULT_READ_TIMEOUT = 60
45
51
 
46
52
  attr_reader :size, :pos, :requests
47
53
  alias tell pos
@@ -50,8 +56,22 @@ module Ziperu
50
56
  # `url` (a String or URI) to fetch over HTTP(S) with `headers` sent on
51
57
  # every request; or, with no url, `size:` and a block that returns
52
58
  # `length` bytes from `offset`.
59
+ #
60
+ # Redirects are followed, but `headers` (credentials, typically) go
61
+ # only to the scheme, host and port of `url`: not to another origin a
62
+ # redirect leads to, unless `forward_headers: true`. A redirect from
63
+ # https to http is refused.
64
+ #
65
+ # A server that ignores Range sends the whole file, which is kept in
66
+ # memory; past `max_full_download` bytes (64 MB; nil for no limit)
67
+ # that raises instead. Every ranged answer must carry the
68
+ # Content-Range asked for, and when the server gives an ETag (or a
69
+ # Last-Modified time) it must stay the same: a file changed between
70
+ # requests raises rather than being read as a mix of two versions.
53
71
  def initialize(url = nil, headers: {}, size: nil, block_size: DEFAULT_BLOCK_SIZE,
54
- cache_blocks: DEFAULT_CACHE_BLOCKS, open_timeout: 10, read_timeout: 60, &fetch)
72
+ cache_blocks: DEFAULT_CACHE_BLOCKS, open_timeout: DEFAULT_OPEN_TIMEOUT,
73
+ read_timeout: DEFAULT_READ_TIMEOUT, forward_headers: false,
74
+ max_full_download: DEFAULT_MAX_FULL_DOWNLOAD, &fetch)
55
75
  raise ArgumentError, 'give a url or a block, not both' if url && fetch
56
76
  raise ArgumentError, 'give a url, or size: and a block' unless url || (fetch && size)
57
77
  raise ArgumentError, 'block_size must be positive' unless block_size.positive?
@@ -66,7 +86,15 @@ module Ziperu
66
86
  @closed = false
67
87
  if url
68
88
  @uri = URI(url.to_s)
89
+ unless HTTP_SCHEMES.include?(@uri.scheme&.downcase) && @uri.host
90
+ raise ArgumentError, "RemoteIO fetches http and https URLs, not #{url.to_s.inspect}"
91
+ end
92
+
69
93
  @headers = headers
94
+ @headers_origin = origin(@uri)
95
+ @forward_headers = forward_headers
96
+ @max_full_download = max_full_download
97
+ @validator = nil
70
98
  @open_timeout = open_timeout
71
99
  @read_timeout = read_timeout
72
100
  @size = discover_size
@@ -124,8 +152,7 @@ module Ziperu
124
152
 
125
153
  def close
126
154
  @closed = true
127
- @http&.finish if @http&.started?
128
- @http = nil
155
+ disconnect
129
156
  @blocks.clear
130
157
  nil
131
158
  end
@@ -152,7 +179,7 @@ module Ziperu
152
179
  piece = @tail.byteslice(at - @tail_start, finish - at)
153
180
  else
154
181
  index = at / @block_size
155
- load_blocks(index, ((finish - 1) / @block_size))
182
+ load_blocks(index, (finish - 1) / @block_size)
156
183
  block = @blocks[index]
157
184
  offset = at - (index * @block_size)
158
185
  piece = block.byteslice(offset, finish - at)
@@ -175,6 +202,9 @@ module Ziperu
175
202
  index = first
176
203
  while index <= last
177
204
  if @blocks.key?(index)
205
+ # Kept as the most recently used: the caller reads it next, and
206
+ # fetching the blocks after it must not push it out.
207
+ @blocks[index] = @blocks.delete(index)
178
208
  index += 1
179
209
  next
180
210
  end
@@ -197,11 +227,9 @@ module Ziperu
197
227
  if @fetch
198
228
  @fetch.call(offset, length).to_s.b
199
229
  else
200
- http_range("bytes=#{offset}-#{offset + length - 1}", offset)
230
+ http_range(offset, length)
201
231
  end
202
- unless data.bytesize == length
203
- raise Error, "asked for #{length} bytes at offset #{offset}, got #{data.bytesize}"
204
- end
232
+ raise Error, "asked for #{length} bytes at offset #{offset}, got #{data.bytesize}" unless data.bytesize == length
205
233
 
206
234
  data
207
235
  end
@@ -211,58 +239,179 @@ module Ziperu
211
239
  # being what opening an archive reads first.
212
240
  def discover_size
213
241
  @requests += 1
214
- response = request("bytes=-#{TAIL_SIZE}")
242
+ response, body = request("bytes=-#{TAIL_SIZE}", TAIL_SIZE, full: true)
243
+ @validator = validator_of(response)
215
244
  case response
216
245
  when Net::HTTPPartialContent
217
- total = response['content-range'].to_s[%r{/(\d+)\z}, 1]
218
- raise Error, "#{@uri} answered without a usable Content-Range" unless total
246
+ first, last, total = content_range(response)
247
+ unless total && last == total - 1 && last - first + 1 == body.bytesize
248
+ raise Error, "#{@uri} answered a request for its last bytes with " \
249
+ "Content-Range #{response['content-range'].inspect} and #{body.bytesize} bytes"
250
+ end
219
251
 
220
- body = response.body.to_s.b
221
- @tail_start = Integer(total) - body.bytesize
222
- @tail = body
223
- Integer(total)
252
+ keep_tail(body, total)
224
253
  when Net::HTTPRequestedRangeNotSatisfiable
225
254
  # An empty file has no last bytes.
226
255
  0
227
256
  when Net::HTTPOK
228
257
  # The server ignores Range: the whole file came back; keep it.
229
- body = response.body.to_s.b
230
- @tail_start = 0
231
- @tail = body
232
- body.bytesize
258
+ keep_tail(body, body.bytesize)
233
259
  else
234
260
  raise Error, "#{@uri} answered #{response.code} #{response.message}"
235
261
  end
236
262
  end
237
263
 
238
- def http_range(range, offset)
239
- response = request(range)
264
+ def http_range(offset, length)
265
+ last = offset + length - 1
266
+ response, body = request("bytes=#{offset}-#{last}", length)
267
+ if response.kind_of?(Net::HTTPPreconditionFailed)
268
+ raise Error, "#{@uri} changed since it was opened (its ETag no longer matches)"
269
+ end
240
270
  unless response.kind_of?(Net::HTTPPartialContent)
241
271
  raise Error, "#{@uri} answered #{response.code} to a Range request at offset #{offset}"
242
272
  end
243
273
 
244
- response.body.to_s.b
274
+ check_unchanged(response)
275
+ first, got_last, total = content_range(response)
276
+ unless first == offset && got_last == last && (total.nil? || total == @size)
277
+ raise Error, "#{@uri} answered a request for bytes #{offset}-#{last} of #{@size} " \
278
+ "with Content-Range #{response['content-range'].inspect}"
279
+ end
280
+
281
+ body
282
+ end
283
+
284
+ # `[first, last, total]` from a 206's Content-Range, total nil for
285
+ # `*`; nil when there is none or it does not parse.
286
+ def content_range(response)
287
+ match = %r{\Abytes (\d+)-(\d+)/(\d+|\*)\z}.match(response['content-range'].to_s.strip)
288
+ return unless match
289
+
290
+ [Integer(match[1]), Integer(match[2]), match[3] == '*' ? nil : Integer(match[3])]
291
+ end
292
+
293
+ # What identifies the version of the file first read: its ETag, or
294
+ # failing that its Last-Modified time.
295
+ def validator_of(response)
296
+ if (etag = response['etag'])
297
+ [:etag, etag]
298
+ elsif (modified = response['last-modified'])
299
+ [:last_modified, modified]
300
+ end
301
+ end
302
+
303
+ # Raises when an answer names a different version than the first one.
304
+ def check_unchanged(response)
305
+ kind, value = @validator
306
+ now = kind == :etag ? response['etag'] : response['last-modified'] if kind
307
+ return if now.nil? || weak_etag_equal?(now, value)
308
+
309
+ raise Error, "#{@uri} changed since it was opened (#{kind} was #{value}, now #{now})"
310
+ end
311
+
312
+ def weak_etag_equal?(one, other)
313
+ one.delete_prefix('W/') == other.delete_prefix('W/')
245
314
  end
246
315
 
247
316
  # A GET with `Range: range`, following redirects (the URL redirected
248
317
  # to is used from then on, as a presigned S3 link redirects once).
249
- def request(range, redirects = MAX_REDIRECTS)
318
+ # Returns the response and its body, read no further than a range of
319
+ # `wanted` bytes can be, or, with `full:` true, a whole file of
320
+ # `max_full_download`.
321
+ def request(range, wanted, full: false, redirects: MAX_REDIRECTS)
250
322
  http = connection
251
323
  get = Net::HTTP::Get.new(@uri)
252
- @headers.each { |k, v| get[k.to_s] = v.to_s }
324
+ @headers.each { |k, v| get[k.to_s] = v.to_s } if @forward_headers || origin(@uri) == @headers_origin
253
325
  get['range'] = range
254
326
  get['accept-encoding'] = 'identity'
255
- response = http.request(get)
256
- return response unless response.kind_of?(Net::HTTPRedirection)
327
+ # A strong ETag pins the version: a server that has a newer one
328
+ # answers 412 rather than its bytes.
329
+ kind, value = @validator
330
+ get['if-match'] = value if kind == :etag && !value.start_with?('W/')
331
+ response = body = nil
332
+ http.request(get) do |res|
333
+ response = res
334
+ body = read_limited(res, wanted, full) unless res.kind_of?(Net::HTTPRedirection)
335
+ end
336
+ return [response, body] unless response.kind_of?(Net::HTTPRedirection)
257
337
  raise Error, "too many redirects from #{@uri}" if redirects.zero?
258
338
 
259
- location = URI.join(@uri.to_s, response['location'].to_s)
260
- if location.host != @uri.host || location.port != @uri.port || location.scheme != @uri.scheme
261
- @http&.finish if @http&.started?
262
- @http = nil
263
- end
339
+ location = redirect_target(response['location'])
340
+ disconnect if origin(location) != origin(@uri)
264
341
  @uri = location
265
- request(range, redirects - 1)
342
+ request(range, wanted, full: full, redirects: redirects - 1)
343
+ rescue Error
344
+ # A body left half read cannot be followed by another request.
345
+ disconnect
346
+ raise
347
+ end
348
+
349
+ # The body of `response`, raising once it is longer than it can be.
350
+ def read_limited(response, wanted, full)
351
+ limit =
352
+ case response
353
+ when Net::HTTPPartialContent then wanted
354
+ when Net::HTTPOK then full ? @max_full_download : ERROR_BODY_LIMIT
355
+ else ERROR_BODY_LIMIT
356
+ end
357
+ body = +''.b
358
+ check_length = lambda do |length|
359
+ return if limit.nil? || length <= limit
360
+
361
+ raise Error, too_long(response, limit)
362
+ end
363
+ check_length.call(response.content_length) if response.content_length
364
+ response.read_body do |chunk|
365
+ body << chunk
366
+ check_length.call(body.bytesize)
367
+ end
368
+ body
369
+ end
370
+
371
+ def too_long(response, limit)
372
+ case response
373
+ when Net::HTTPOK
374
+ "#{@uri} ignores Range requests and sent the whole file, which is over max_full_download " \
375
+ "(#{limit} bytes); raise that limit, or download the file first"
376
+ when Net::HTTPPartialContent
377
+ "#{@uri} sent more than the #{limit} bytes asked for"
378
+ else
379
+ "#{@uri} answered #{response.code} #{response.message}"
380
+ end
381
+ end
382
+
383
+ # Where a redirect leads, if it may be followed: http or https only,
384
+ # and never from https down to http.
385
+ def redirect_target(header)
386
+ location = URI.join(@uri.to_s, header.to_s)
387
+ scheme = location.scheme&.downcase
388
+ unless HTTP_SCHEMES.include?(scheme) && location.host
389
+ raise Error, "#{@uri} redirected to #{location}, which is not an http or https URL"
390
+ end
391
+ if @uri.scheme.downcase == 'https' && scheme == 'http'
392
+ raise Error, "#{@uri} redirected from https to #{location}; refusing to drop to plain http"
393
+ end
394
+
395
+ location
396
+ rescue URI::Error => e
397
+ raise Error, "#{@uri} redirected to an unusable location #{header.inspect}: #{e.message}"
398
+ end
399
+
400
+ # Scheme, host and port: where headers given for one URL may go.
401
+ def origin(uri)
402
+ [uri.scheme.downcase, uri.host.downcase, uri.port]
403
+ end
404
+
405
+ # Keeps `body`, the last bytes of a file of `total` bytes. Returns `total`.
406
+ def keep_tail(body, total)
407
+ @tail_start = total - body.bytesize
408
+ @tail = body
409
+ total
410
+ end
411
+
412
+ def disconnect
413
+ @http&.finish if @http&.started?
414
+ @http = nil
266
415
  end
267
416
 
268
417
  def connection