Skip to content

fix: correctly handle HTTP suffix-byte-range requests (bytes=-N)#36

Open
dreamcreated wants to merge 1 commit intowindoze95:mainfrom
dreamcreated:fix/http-range-suffix-byte-range
Open

fix: correctly handle HTTP suffix-byte-range requests (bytes=-N)#36
dreamcreated wants to merge 1 commit intowindoze95:mainfrom
dreamcreated:fix/http-range-suffix-byte-range

Conversation

@dreamcreated
Copy link

Problem

Fixes #29

In app/services/media_server.py, the build_range_response function incorrectly handles suffix-byte-range requests (e.g. bytes=-500).

When a client sends Range: bytes=-500 (meaning "give me the last 500 bytes"), the old code splits on - to get ["", "500"]. Because parts[0] is empty, start was set to 0 and end to 500 — returning the first 501 bytes instead of the last 500.

This breaks clients that seek to the end of a file or read trailing metadata (e.g. MP4 moov atoms, ID3 tags).

Fix

Add a check for the suffix-byte-range format before the normal parse:

if not parts[0] and len(parts) > 1 and parts[1]:
    # Suffix-byte-range: bytes=-N means the last N bytes
    start = max(0, file_size - int(parts[1]))
    end = file_size - 1
else:
    start = int(parts[0]) if parts[0] else 0
    end = int(parts[1]) if len(parts) > 1 and parts[1] else file_size - 1

Tests

Verified with all four cases:

Range header file_size Expected Result
bytes=-500 10000 9500–9999
bytes=0-1023 10000 0–1023
bytes=5000- 10000 5000–9999
bytes=-99999 10000 0–9999 (clamped)

When a client sends 'Range: bytes=-500' (last 500 bytes), the previous
code split on '-' and got ['', '500']. Since parts[0] was empty, start
was set to 0 and end to 500, returning the first 501 bytes instead of
the last 500.

Fix by detecting the suffix-byte-range format (empty start, non-empty
end) and computing: start = max(0, file_size - N), end = file_size - 1.

Fixes windoze95#29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: HTTP Range header incorrectly parses suffix-byte-range requests

1 participant