Skip to content

Commit

Permalink
Ignore Range header if served file is 0 bytes
Browse files Browse the repository at this point in the history
Normally Rack::Files truncates a byte range to fit a file's contents as long as
at least some bytes are within range. However, an empty (0 byte) file is a
special case. Previously, empty files requested with a Range header always
resulted in a 416 error. This changes 0 byte files to ignore the Range header
and return the empty file.

This improves compatibility with clients that speculatively request files with
byte ranges.
  • Loading branch information
zarqman committed Feb 25, 2024
1 parent 1848851 commit de2687b
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions lib/rack/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@ def byte_ranges(env, size)

def get_byte_ranges(http_range, size)
# See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
return nil if size.zero?
return nil unless http_range && http_range =~ /bytes=([^;]+)/
ranges = []
$1.split(/,\s*/).each do |range_spec|
Expand Down
Empty file.
9 changes: 9 additions & 0 deletions test/spec_files.rb
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,15 @@ def filesize(_); 10000 end
res["content-range"].must_equal "bytes */209"
end

it "ignores range when file is 0 bytes" do
env = Rack::MockRequest.env_for("/cgi/assets/images/favicon.ico")
env["HTTP_RANGE"] = "bytes=0-1234"
res = Rack::MockResponse.new(*files(DOCROOT).call(env))

res.status.must_equal 200
res["content-range"].must_be_nil
end

it "support custom http headers" do
env = Rack::MockRequest.env_for("/cgi/test")
status, heads, _ = files(DOCROOT, 'cache-control' => 'public, max-age=38',
Expand Down
10 changes: 5 additions & 5 deletions test/spec_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -733,11 +733,11 @@ def initialize(*)
end

it "handle byte ranges of empty files" do
Rack::Utils.get_byte_ranges("bytes=123-456", 0).must_equal []
Rack::Utils.get_byte_ranges("bytes=0-", 0).must_equal []
Rack::Utils.get_byte_ranges("bytes=-100", 0).must_equal []
Rack::Utils.get_byte_ranges("bytes=0-0", 0).must_equal []
Rack::Utils.get_byte_ranges("bytes=-0", 0).must_equal []
Rack::Utils.get_byte_ranges("bytes=123-456", 0).must_be_nil
Rack::Utils.get_byte_ranges("bytes=0-", 0).must_be_nil
Rack::Utils.get_byte_ranges("bytes=-100", 0).must_be_nil
Rack::Utils.get_byte_ranges("bytes=0-0", 0).must_be_nil
Rack::Utils.get_byte_ranges("bytes=-0", 0).must_be_nil
end
end

Expand Down

0 comments on commit de2687b

Please sign in to comment.