mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 15:35:06 +00:00
218 lines
9.2 KiB
Python
218 lines
9.2 KiB
Python
"""The one verdict on a ranged answer: may this response's bytes go at the offset the request asked for."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from collections.abc import Mapping
|
|
from dataclasses import dataclass
|
|
from enum import Enum
|
|
from typing import Any
|
|
|
|
ContentRange = tuple[int, int, int | None]
|
|
|
|
|
|
class Mode(Enum):
|
|
"""What the request asks for.
|
|
|
|
RESUME is a whole file, from byte 0 or from the end of its partial. PART is one sub-range of a parallel ranged
|
|
download, written at its offset in a shared file. ITEM is a byte-range slice that the item's own Range names.
|
|
"""
|
|
|
|
RESUME = "resume"
|
|
PART = "part"
|
|
ITEM = "item"
|
|
|
|
|
|
class Verdict(Enum):
|
|
"""What to do with the body.
|
|
|
|
WRITE it from the request start (byte 0 in RESUME) or APPEND it to the partial. FINISHED: the partial is whole.
|
|
RESTART discards the partial and fails the attempt; REJECT fails the attempt and keeps the partial.
|
|
"""
|
|
|
|
WRITE = "write"
|
|
APPEND = "append"
|
|
FINISHED = "finished"
|
|
RESTART = "restart"
|
|
REJECT = "reject"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Answer:
|
|
"""A verdict with the complete length known after it, the body length to expect, and the error line.
|
|
|
|
``content_range`` is the response's Content-Range only when the verdict proved that it answers the request.
|
|
"""
|
|
|
|
verdict: Verdict
|
|
total: int | None
|
|
length: int
|
|
content_range: ContentRange | None = None
|
|
reason: str = ""
|
|
|
|
|
|
def _range_value(headers: Mapping[str, Any] | None) -> str | None:
|
|
"""The value of a Range header in ``headers``, any case. Gives None when there is none."""
|
|
return next((str(v) for k, v in (headers or {}).items() if str(k).lower() == "range"), None)
|
|
|
|
|
|
def has_range_header(item: dict[str, Any]) -> bool:
|
|
"""True when a URL item's per-request headers already carry a Range.
|
|
|
|
Such an item is itself a byte-range slice of a larger resource (DASH SegmentBase,
|
|
HLS EXT-X-BYTERANGE). Probing or part-mode would clobber that Range and fetch the
|
|
wrong bytes, so ranged-parallel strategies must skip these items entirely.
|
|
"""
|
|
return _range_value(item.get("headers")) is not None
|
|
|
|
|
|
def range_answer(
|
|
mode: Mode,
|
|
headers: Mapping[str, Any] | None,
|
|
status: int,
|
|
content_range: str | bytes | None,
|
|
*,
|
|
length: int = 0,
|
|
encoded: bool = False,
|
|
total: int | None = None,
|
|
part: tuple[int, int] | None = None,
|
|
) -> Answer:
|
|
"""Judge a response to a request with ``headers`` from its status and Content-Range header.
|
|
|
|
``length`` is the declared body length (0 when unknown), ``total`` the complete length known before this
|
|
response, and ``part`` the inclusive ``(offset, end)`` of the part a PART request belongs to. A 416 to a
|
|
resume gets FINISHED or RESTART; the caller raises any other HTTP error status before it acts on the verdict.
|
|
"""
|
|
value = _range_value(headers) or ""
|
|
if isinstance(content_range, bytes):
|
|
content_range = content_range.decode("latin1", "replace")
|
|
header = str(content_range or "").strip()
|
|
if mode is Mode.PART:
|
|
if part is None:
|
|
raise ValueError("a PART answer needs the part's (offset, end)")
|
|
return _part_answer(value, status, header, length, total, part)
|
|
if mode is Mode.ITEM:
|
|
return _item_answer(value, status, header, length, encoded, total)
|
|
return _resume_answer(value, status, header, length, encoded, total)
|
|
|
|
|
|
def _resume_answer(value: str, status: int, header: str, length: int, encoded: bool, total: int | None) -> Answer:
|
|
"""A 416 at the partial's end finishes it; a 206 must start at the partial or prove the whole body from zero.
|
|
|
|
Some servers answer ``bytes=X-`` with a 206 for the whole resource, which is byte-identical to a 200.
|
|
"""
|
|
requested = _request_range(value)
|
|
start = requested[0] if requested else 0
|
|
if start and status == 416:
|
|
complete = _unsatisfied_length(header)
|
|
if complete == start and total in (None, start):
|
|
return Answer(Verdict.FINISHED, total, length)
|
|
reason = f"resume from byte {start} got a 416, complete length {complete}"
|
|
return Answer(Verdict.RESTART, total, length, reason=reason)
|
|
content_range = _parse_content_range(header)
|
|
if start and status == 206:
|
|
if content_range is not None and content_range[0] == start:
|
|
if content_range[2] is not None:
|
|
total = content_range[2]
|
|
if encoded:
|
|
return Answer(
|
|
Verdict.RESTART, total, length, reason=f"resume from byte {start} came back content-encoded"
|
|
)
|
|
return Answer(Verdict.APPEND, total, length, content_range)
|
|
whole = (
|
|
content_range is not None
|
|
and content_range[2] is not None
|
|
and content_range[:2] == (0, content_range[2] - 1)
|
|
)
|
|
if not whole:
|
|
reason = f"resume from byte {start} got Content-Range {content_range!r}"
|
|
return Answer(Verdict.RESTART, total, length, reason=reason)
|
|
if total is None and status == 200:
|
|
return Answer(Verdict.WRITE, length or None, length)
|
|
if total is None and status == 206 and content_range is not None:
|
|
if content_range[0] != 0:
|
|
return Answer(
|
|
Verdict.REJECT, total, length, reason=f"206 body starts at byte {content_range[0]}, expected 0"
|
|
)
|
|
return Answer(Verdict.WRITE, content_range[2], length, content_range)
|
|
return Answer(Verdict.WRITE, total, length)
|
|
|
|
|
|
def _part_answer(value: str, status: int, header: str, length: int, total: int | None, part: tuple[int, int]) -> Answer:
|
|
"""A part needs a 206 at its own start that ends within the request, from a resource still longer than the part.
|
|
|
|
A wrong start lands bytes at the wrong offset in the shared file, an end past the request spills into a sibling
|
|
part, and a complete length at or below the part's end means the resource changed under the part plan.
|
|
"""
|
|
offset, end = part
|
|
if status != 206:
|
|
return Answer(Verdict.REJECT, total, length, reason=f"expected 206 for ranged part, got {status}")
|
|
requested = _request_range(value)
|
|
content_range = _parse_content_range(header)
|
|
if (
|
|
requested is None
|
|
or content_range is None
|
|
or content_range[0] != requested[0]
|
|
or (requested[1] is not None and content_range[1] > requested[1])
|
|
or (content_range[2] is not None and content_range[2] <= end)
|
|
):
|
|
return Answer(Verdict.REJECT, total, length, reason=f"part {offset}-{end} got Content-Range {content_range!r}")
|
|
return Answer(Verdict.WRITE, total, length, content_range)
|
|
|
|
|
|
def _item_answer(value: str, status: int, header: str, length: int, encoded: bool, total: int | None) -> Answer:
|
|
"""A slice needs a 206 for its own range, or a 200 whose whole body is exactly the slice from byte 0.
|
|
|
|
RFC 9110 lets a server ignore Range and answer 200 with the whole resource, and clamps a range end past the
|
|
resource to its last byte. A slice whose Range does not parse as ``bytes=start-...`` takes any 206 unproven.
|
|
"""
|
|
if status != 206:
|
|
whole = status == 200 and re.fullmatch(r"bytes=(\d+)-(\d+)", value.strip())
|
|
if whole and length > 0 and int(whole[1]) == 0 and length == int(whole[2]) + 1:
|
|
return Answer(Verdict.WRITE, total, length)
|
|
return Answer(Verdict.REJECT, total, length, reason=f"expected 206 for byte-range segment, got {status}")
|
|
requested = _request_range(value)
|
|
if requested is None:
|
|
return Answer(Verdict.WRITE, total, length)
|
|
start, end = requested
|
|
content_range = _parse_content_range(header)
|
|
if (
|
|
content_range is None
|
|
or content_range[0] != start
|
|
or not (
|
|
end is None
|
|
or content_range[1] == end
|
|
or (content_range[2] is not None and content_range[1] == content_range[2] - 1 and end >= content_range[2])
|
|
)
|
|
):
|
|
expected = f"{start}-{end if end is not None else ''}"
|
|
return Answer(
|
|
Verdict.REJECT,
|
|
total,
|
|
length,
|
|
reason=f"byte-range segment got Content-Range {content_range!r}, expected {expected}",
|
|
)
|
|
return Answer(Verdict.WRITE, total, length if encoded else content_range[1] - content_range[0] + 1, content_range)
|
|
|
|
|
|
def _request_range(value: str) -> tuple[int, int | None] | None:
|
|
"""A Range value as ``(start, end)``, ``end`` None when open-ended. Gives None when not ``bytes=start-...``."""
|
|
match = re.match(r"bytes=(\d+)-(\d+)?", value.strip())
|
|
if not match:
|
|
return None
|
|
return int(match.group(1)), int(match.group(2)) if match.group(2) else None
|
|
|
|
|
|
def _parse_content_range(value: str) -> ContentRange | None:
|
|
"""A 206's Content-Range as ``(start, end, total)``, ``total`` None for ``*``. Gives None when absent or unparseable."""
|
|
match = re.fullmatch(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", value, re.IGNORECASE)
|
|
if not match:
|
|
return None
|
|
return int(match.group(1)), int(match.group(2)), None if match.group(3) == "*" else int(match.group(3))
|
|
|
|
|
|
def _unsatisfied_length(value: str) -> int | None:
|
|
"""A 416's ``bytes */N`` Content-Range as N. Gives None when absent or unknown."""
|
|
match = re.fullmatch(r"bytes\s+\*/(\d+)", value, re.IGNORECASE)
|
|
return int(match.group(1)) if match else None
|