Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion lib/net/http/generic_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,33 @@ def send_request_with_body_stream(sock, ver, path, f)
IO.copy_stream(f, chunker)
chunker.finish
else
IO.copy_stream(f, sock)
# Copy only the announced length. Bytes past it would sit on a
# keep-alive socket and be parsed as the next request (net-http#376).
expected = content_length()
copied = IO.copy_stream(f, sock, expected)
if copied != expected || body_stream_has_more?(f)
raise ArgumentError,
"body stream length does not match Content-Length (#{expected})"
end
end
end

# True when +io+ already has another byte after +content_length+ bytes
# were copied. A pipe that has not produced that byte yet is not treated
# as longer: reading it would block, and the surplus was not written.
def body_stream_has_more?(io)
if io.respond_to?(:read_nonblock)
extra = io.read_nonblock(1, exception: false)
return false if extra.nil? || extra == :wait_readable
return !extra.empty? if extra.is_a?(String)
false
elsif io.respond_to?(:eof?)
!io.eof?
else
false
end
rescue EOFError, IO::WaitReadable, Errno::EAGAIN, Errno::EWOULDBLOCK
false
end

def send_request_with_body_data(sock, ver, path, params)
Expand Down
46 changes: 46 additions & 0 deletions test/net/http/test_http_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,50 @@ def test_chunked_request_omits_conflicting_content_length
assert_match(/Transfer-Encoding: chunked/i, header)
assert_no_match(/Content-Length/i, header)
end

def exec_to_pipe(req)
r, w = IO.pipe
w.define_singleton_method(:continue_timeout) { nil }
error = nil
begin
req.exec(w, '1.1', '/')
rescue ArgumentError
error = $!
ensure
w.close
end
[error, r.read]
ensure
r.close if r && !r.closed?
end

def test_body_stream_matches_content_length
req = Net::HTTP::Post.new('/')
req.body_stream = StringIO.new('hello')
req.content_length = 5

error, captured = exec_to_pipe(req)
assert_nil error
assert_equal 'hello', captured.split("\r\n\r\n", 2).last
end

def test_body_stream_longer_than_content_length_is_not_written
req = Net::HTTP::Post.new('/')
req.body_stream = StringIO.new("AAAAA" + "GET /admin HTTP/1.1\r\n\r\n")
req.content_length = 5

error, captured = exec_to_pipe(req)
assert_kind_of ArgumentError, error
assert_equal 'AAAAA', captured.split("\r\n\r\n", 2).last
assert_not_match(/GET \/admin/, captured)
end

def test_body_stream_shorter_than_content_length
req = Net::HTTP::Post.new('/')
req.body_stream = StringIO.new('ab')
req.content_length = 5

error, _captured = exec_to_pipe(req)
assert_kind_of ArgumentError, error
end
end