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
2 changes: 2 additions & 0 deletions CHANGES/14124.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed :class:`aiohttp.web.FileResponse` returning HTTP 416 for valid, satisfiable
requests for multiple byte ranges by serving the entire file instead -- by :user:`emadleo13`.
1 change: 1 addition & 0 deletions CHANGES/14174.bugfix.rst
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ Earle Lowe
Eduard Iskandarov
Eli Ribble
Elizabeth Leddy
Emad Bashari
Emil Melnikov
Enrique Saez
Eric Sheng
Expand Down
59 changes: 56 additions & 3 deletions aiohttp/web_fileresponse.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,52 @@ def _etag_match(etag_value: str, etags: tuple[ETag, ...], *, weak: bool) -> bool
etag.value == etag_value for etag in etags if weak or not etag.is_weak
)

@staticmethod
def _is_satisfiable_multi_range(range_header: str, file_size: int) -> bool:
unit, separator, ranges = range_header.partition("=")
if separator != "=" or unit.lower() != "bytes" or "," not in ranges:
return False

def is_ascii_digits(value: str) -> bool:
return value.isascii() and value.isdecimal()

def less_than(left: str, right: str) -> bool:
left = left.lstrip("0") or "0"
right = right.lstrip("0") or "0"
return (len(left), left) < (len(right), right)

satisfiable = False
file_size_text = str(file_size)

empty_members = 0
for byte_range in ranges.split(","):
byte_range = byte_range.strip(" \t")
if not byte_range:
# RFC 9110 permits a reasonable number of empty list members.
empty_members += 1
if empty_members > 8:
return False
continue

first, dash, last = byte_range.partition("-")

if not dash or "-" in last or not (first or last):
return False
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

if (first and not is_ascii_digits(first)) or (
last and not is_ascii_digits(last)
):
return False

if first:
if last and less_than(last, first):
return False
satisfiable |= less_than(first, file_size_text)
else:
satisfiable |= file_size > 0 and bool(last.lstrip("0"))

return satisfiable

async def _not_modified(
self, request: "BaseRequest", etag_value: str, last_modified: float
) -> AbstractStreamWriter | None:
Expand Down Expand Up @@ -310,6 +356,7 @@ async def _prepare_open_file(
file_mtime: float = st.st_mtime
count: int = file_size
start: int | None = None
end: int | None = None
etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}"

# https://www.rfc-editor.org/info/rfc9110/#name-if-range
Expand All @@ -336,9 +383,15 @@ async def _prepare_open_file(
# if True but Range header missing
# return 200
try:
rng = request.http_range
start = rng.start
end: int | None = rng.stop
if self._is_satisfiable_multi_range(
request.headers.get(hdrs.RANGE, ""), file_size
):
# Multipart responses are unsupported, so ignore valid ranges.
start = end = None
else:
rng = request.http_range
start = rng.start
end = rng.stop
except ValueError:
# https://tools.ietf.org/html/rfc7233:
# A server generating a 416 (Range Not Satisfiable) response to
Expand Down
5 changes: 5 additions & 0 deletions docs/web_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,11 @@ and :ref:`aiohttp-web-signals` handlers::

Supports the ``Content-Range`` and ``If-Range`` HTTP Headers in requests.

Valid requests for multiple byte ranges are ignored and the entire file is
served when at least one range is satisfiable. Malformed or wholly
unsatisfiable range sets receive a ``416`` response.
A limited number of empty range-list members are ignored.

The actual :attr:`body` sending happens in overridden :meth:`~StreamResponse.prepare`.

:param path: Path to file. Accepts both :class:`str` and :class:`pathlib.Path`.
Expand Down
89 changes: 89 additions & 0 deletions tests/test_web_sendfile_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,95 @@ async def handler(request: web.Request) -> web.FileResponse:
await client.close()


@pytest.mark.parametrize(
"range_header",
[
"bytes=0-1,4-5",
"bytes=0-1,",
"bytes=,0-1",
"bytes=0-1,,4-5",
"bytes=0-1, \t ,4-5",
"bytes=0-1,4-5,",
"bytes=0-1,,,,,,,,,4-5",
"bytes=0-1, 4-5",
"bytes=0-1,\t4-5",
"BYTES=0-1,4-5",
"bytes=100-200,0-1",
"bytes=0-1,100-200",
"bytes=100-,4-",
"bytes=100-,-2",
"bytes=-0,0-1",
],
)
async def test_static_file_multiple_ranges_fall_back_to_full_response(
aiohttp_client: AiohttpClient,
sender: _Sender,
tmp_path: pathlib.Path,
range_header: str,
) -> None:
filepath = tmp_path / "ten.bin"
filepath.write_bytes(b"0123456789")

async def handler(request: web.Request) -> web.FileResponse:
return sender(filepath, chunk_size=16)

app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)

async with client.get("/", headers={"Range": range_header}) as response:
assert response.status == 200
assert "Content-Range" not in response.headers
assert response.headers["Content-Length"] == "10"
assert await response.read() == b"0123456789"

await client.close()


@pytest.mark.parametrize(
"range_header",
[
"blocks=0-1,4-5",
"bytes=0-1,a-b",
"bytes=0-1,5-4",
"bytes=0-1,0--1",
"bytes=0-1,-",
"bytes=,,",
"bytes=0-1,,a-b",
"bytes=0-1,,,,,,,,,,4-5",
"bytes=10-11,,20-21",
"bytes=0-1, 4 -5",
"bytes=0-1,+4-5",
"bytes=0-1,\u0664-\u0665",
"bytes=10-11,20-21",
"bytes=10-,20-",
"bytes=-0,10-",
"bytes=-0,-0",
],
)
async def test_static_file_invalid_multiple_ranges(
aiohttp_client: AiohttpClient,
sender: _Sender,
tmp_path: pathlib.Path,
range_header: str,
) -> None:
filepath = tmp_path / "ten.bin"
filepath.write_bytes(b"0123456789")

async def handler(request: web.Request) -> web.FileResponse:
return sender(filepath, chunk_size=16)

app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)

async with client.get("/", headers={"Range": range_header}) as response:
assert response.status == 416
assert response.headers["Content-Range"] == "bytes */10"

await client.close()


async def test_static_file_invalid_range(
aiohttp_client: AiohttpClient, sender: _Sender
) -> None:
Expand Down
Loading