@@ -15,6 +15,9 @@ module Body
1515 class Chunked < HTTP ::Body ::Readable
1616 CRLF = "\r \n "
1717
18+ # The maximum amount of body data returned by a single read.
19+ BLOCK_SIZE = 1024 * 64
20+
1821 # Initialize the chunked body.
1922 #
2023 # @parameter connection [Protocol::HTTP1::Connection] the connection to read the body from.
@@ -27,6 +30,7 @@ def initialize(connection, headers)
2730
2831 @length = 0
2932 @count = 0
33+ @remaining = nil
3034 end
3135
3236 # @attribute [Integer] the number of chunks read so far.
@@ -69,15 +73,39 @@ def close(error = nil)
6973 # @returns [String | Nil] the next chunk of data, or `nil` if the body is finished.
7074 # @raises [EOFError] if the connection is closed before the expected length is read.
7175 def read
72- if !@finished
73- if @connection
76+ while !@finished
77+ unless @connection
78+ raise EOFError , "connection closed before expected length was read!"
79+ end
80+
81+ if @remaining
82+ if @remaining > 0
83+ chunk = @connection . readpartial ( [ @remaining , BLOCK_SIZE ] . min )
84+ @remaining -= chunk . bytesize
85+ @length += chunk . bytesize
86+
87+ return chunk
88+ end
89+
90+ terminator = @connection . read ( CRLF . bytesize )
91+
92+ unless terminator &.bytesize == CRLF . bytesize
93+ raise EOFError , "connection closed before expected length was read!"
94+ end
95+
96+ unless terminator == CRLF
97+ raise BadRequest , "Invalid chunk terminator: #{ terminator . inspect } "
98+ end
99+
100+ @remaining = nil
101+ @count += 1
102+ else
74103 length , _extensions = @connection . read_line . split ( ";" , 2 )
75104
76105 unless length =~ VALID_CHUNK_LENGTH
77106 raise BadRequest , "Invalid chunk length: #{ length . inspect } "
78107 end
79108
80- # It is possible this line contains chunk extension, so we use `to_i` to only consider the initial integral part:
81109 length = Integer ( length , 16 )
82110
83111 if length == 0
@@ -91,27 +119,16 @@ def read
91119 return nil
92120 end
93121
94- # Read trailing CRLF:
95- chunk = @connection . read ( length + 2 )
96-
97- if chunk . bytesize == length + 2
98- # ...and chomp it off:
99- chunk . chomp! ( CRLF )
100-
101- @length += length
102- @count += 1
103-
104- return chunk
105- else
106- # The connection has been closed before we have read the requested length:
107- @connection . close_read
108- @connection = nil
109- end
122+ @remaining = length
110123 end
111-
112- # If the connection has been closed before we have read the final chunk, raise an error:
113- raise EOFError , "connection closed before expected length was read!"
114124 end
125+ rescue EOFError
126+ if connection = @connection
127+ @connection = nil
128+ connection . close_read
129+ end
130+
131+ raise EOFError , "connection closed before expected length was read!"
115132 end
116133
117134 # @returns [String] a human-readable representation of the body.
0 commit comments