diff --git a/CHANGELOG.md b/CHANGELOG.md index 416ad1e2..218fc9a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 JVM could garbage-collect llhttp's native callback trampolines while a parser was still in use, after which `llhttp_execute` succeeded without invoking any callbacks. Callback procs are now retained for the lifetime of the parser. +- With `auto_inflate`, each `readpartial` (and each chunk yielded by + `Body#each`) now returns at most about 4 MiB of decompressed data. + Previously a whole network read was inflated at once, so a highly + compressed 16 KiB read could expand to roughly 16 MiB in a single chunk, + defeating streaming as a way to bound memory use. Compressed input is now + inflated in 4 KiB slices. ([#865]) ## [6.0.4] - 2026-07-14 @@ -343,6 +349,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#785]: https://github.com/httprb/http/issues/785 [#826]: https://github.com/httprb/http/issues/826 [#841]: https://github.com/httprb/http/pull/841 +[#865]: https://github.com/httprb/http/pull/865 [#863]: https://github.com/httprb/http/issues/863 [GHSA-r98x-p6m8-xcrv]: https://github.com/httprb/http/security/advisories/GHSA-r98x-p6m8-xcrv diff --git a/lib/http/response/inflater.rb b/lib/http/response/inflater.rb index 18854457..b063a279 100644 --- a/lib/http/response/inflater.rb +++ b/lib/http/response/inflater.rb @@ -6,6 +6,16 @@ module HTTP class Response # Decompresses gzip/deflate response body streams class Inflater + # Largest slice of compressed input handed to zlib at once + # + # Deflate can expand input by roughly 1032:1 at most, so a 4 KiB + # slice caps each decompressed chunk at about 4 MiB, however much + # compressed data a single read from the connection returns. Each + # slice is a call to zlib, which has a fixed cost, so smaller slices + # inflate a large body noticeably slower. + INPUT_SLICE_SIZE = 4_096 + private_constant :INPUT_SLICE_SIZE + # The underlying connection # # @example @@ -25,10 +35,17 @@ class Inflater # @api public def initialize(connection) @connection = connection + @input = "" + @offset = 0 end # Read and inflate a chunk of the response body # + # Compressed input is inflated one slice at a time, so each call + # returns a bounded amount of decompressed data even when the + # compression ratio is extreme. Input left over from an earlier + # read is consumed before the connection is read again. + # # @example # inflater.readpartial # => "decompressed data" # @@ -36,19 +53,59 @@ def initialize(connection) # @raise [EOFError] when no more data left # @api public def readpartial(*) - chunk = @connection.readpartial(*) - zstream.inflate(chunk) - rescue EOFError - unless zstream.closed? - zstream.finished? ? zstream.finish : zstream.reset - zstream.close + loop do + fill_input(*) if @offset >= @input.bytesize + output = zstream.inflate(next_slice) + return output unless output.empty? end - + rescue EOFError + close_zstream raise end private + # Flush and close the zlib stream once the connection is exhausted + # @return [void] + # @api private + def close_zstream + return if zstream.closed? + + zstream.finished? ? zstream.finish : zstream.reset + zstream.close + end + + # Replace the consumed input with a fresh read from the connection + # + # A read into a caller-supplied outbuf is copied, because the caller + # may reuse the outbuf while part of its input is still pending. + # Without one, the connection returns a new string, which is kept + # as it is. + # + # @return [void] + # @api private + def fill_input(*args) + chunk = @connection.readpartial(*args) + @input = args[1] ? chunk.b : chunk + @offset = 0 + end + + # Take the next slice of pending compressed input + # + # A read that fits in one slice is used whole, without slicing it. + # + # @return [String] + # @api private + def next_slice + slice = if @offset.zero? && @input.bytesize <= INPUT_SLICE_SIZE + @input + else + String(@input.byteslice(@offset, INPUT_SLICE_SIZE)) + end + @offset += INPUT_SLICE_SIZE + slice + end + # Return the zlib inflate stream # @return [Zlib::Inflate] # @api private diff --git a/sig/http.rbs b/sig/http.rbs index ddf820a3..d76fe942 100644 --- a/sig/http.rbs +++ b/sig/http.rbs @@ -1049,7 +1049,11 @@ module HTTP end class Inflater + INPUT_SLICE_SIZE: Integer + @zstream: Zlib::Inflate? + @input: String + @offset: Integer attr_reader connection: untyped @@ -1058,6 +1062,9 @@ module HTTP private + def close_zstream: () -> void + def fill_input: (?Integer size, ?String? outbuf) -> void + def next_slice: () -> String def zstream: () -> Zlib::Inflate end diff --git a/test/http/response/inflater_test.rb b/test/http/response/inflater_test.rb new file mode 100644 index 00000000..ef5f342e --- /dev/null +++ b/test/http/response/inflater_test.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +require "test_helper" +require "zlib" +require "stringio" + +class HTTPResponseInflaterTest < Minitest::Test + cover "HTTP::Response::Inflater*" + + # Upper bound on decompressed bytes from one 4 KiB slice of deflate input + MAX_CHUNK_SIZE = 4_096 * 1_032 + + def gzip(data) + io = StringIO.new("".b) + gz = Zlib::GzipWriter.new(io) + gz.write(data) + gz.close + io.string + end + + def connection_for(chunks, reads: []) + fake(readpartial: proc { |*args| + reads << args + chunks.shift || raise(EOFError) + }) + end + + def read_all(inflater) + parts = [] + loop { parts << inflater.readpartial } + rescue EOFError + parts + end + + def test_bounds_each_chunk_inflated_from_a_highly_compressed_read + data = "\0" * (16 * 1_024 * 1_024) + inflater = HTTP::Response::Inflater.new(connection_for([gzip(data)])) + parts = read_all(inflater) + + assert_operator parts.map(&:bytesize).max, :<=, MAX_CHUNK_SIZE + assert_equal data.bytesize, parts.sum(&:bytesize) + end + + def test_inflates_data_split_across_slices_and_reads + data = Random.new(42).bytes(5_000) * 3 + compressed = gzip(data) + chunks = [compressed[0, 3_000], compressed[3_000..]] + inflater = HTTP::Response::Inflater.new(connection_for(chunks)) + + assert_equal data, read_all(inflater).join + end + + def test_consumes_pending_input_before_reading_the_connection_again + data = Random.new(42).bytes(10_000) + reads = [] + inflater = HTTP::Response::Inflater.new(connection_for([gzip(data)], reads: reads)) + + inflater.readpartial + inflater.readpartial + + assert_equal 1, reads.size + end + + def test_keeps_reading_when_a_slice_yields_no_output + compressed = gzip("hello") + chunks = [compressed[0, 10], compressed[10..]] + inflater = HTTP::Response::Inflater.new(connection_for(chunks)) + + assert_equal "hello", inflater.readpartial + end + + def test_forwards_read_arguments_to_the_connection + reads = [] + inflater = HTTP::Response::Inflater.new(connection_for([gzip("hello")], reads: reads)) + + inflater.readpartial(512) + + assert_equal [[512]], reads + end + + def test_copies_reads_so_a_reused_outbuf_cannot_corrupt_pending_input + data = Random.new(42).bytes(10_000) + compressed = gzip(data) + outbuf = +"" + conn = fake(readpartial: proc { |_size, buf| + raise EOFError if compressed.empty? + + buf.replace(compressed) + compressed = "" + buf + }) + inflater = HTTP::Response::Inflater.new(conn) + parts = [inflater.readpartial(16_384, outbuf)] + outbuf.replace("garbage") + parts.concat(read_all(inflater)) + + assert_equal data, parts.join + end +end