This one is about a download bug in a reading app I’m building, which fetches books and audiobooks from self-hosted servers (OPDS catalogs and Audiobookshelf), and the small test I ended up with while looking for a fix. I was checking whether the app could tell a finished download from one where the server closed the connection before finishing a chunked response, which the HTTP spec counts as an incomplete message, and it couldn’t, because URLSession reported success for both and the app saved the file either way. So we’ll build a fixture that shows the same thing outside the app, and then look at what curl does with it and why I still didn’t switch to libcurl.
How a chunked body ends
With Transfer-Encoding: chunked, each data chunk starts with its size in hexadecimal, and the body ends with a zero-size chunk, any trailers and an empty line, so a response without trailers finishes with 0\r\n\r\n. If the connection closes before that zero-size chunk arrives, the client has an incomplete message, even when every data byte it was ever going to get is already there.
Building the paired responses
The idea is to make two responses that look the same from the outside, so that the end of the chunked body is the only thing that differs. Both send 100,000 copies of x, the complete one in a single chunk (186a0 in hex) followed by the terminator, and the incomplete one with the first byte in a chunk of its own and the remaining 99,999 bytes (1869f) in a second one, before it closes the connection. The extra chunk costs five bytes of framing, which is exactly the size of the terminator we leave out, so both bodies take 100,014 bytes on the wire (not counting headers) and decode to the same file.
Save this as fixture.py, which writes the whole response straight to a loopback socket, which lets us decide exactly which bytes go out before the connection closes (that’s the reason for not using a server framework here).
from socketserver import BaseRequestHandler, TCPServer
BODY = b"x" * 100_000
def chunk(data):
return f"{len(data):x}\r\n".encode() + data + b"\r\n"
complete = chunk(BODY) + b"0\r\n\r\n"
missing_terminator = chunk(BODY[:1]) + chunk(BODY[1:])
assert len(complete) == len(missing_terminator) == 100_014
chunked = b"Transfer-Encoding: chunked\r\n"
responses = {
b"/complete": (chunked, complete),
b"/missing-terminator": (chunked, missing_terminator),
b"/short-length": (b"Content-Length: 100001\r\n", BODY),
}
class Fixture(BaseRequestHandler):
def handle(self):
self.request.settimeout(5)
with self.request.makefile("rb") as request:
start = request.readline().split()
if len(start) != 3 or start[1] not in responses:
return
for line in request:
if line == b"\r\n":
break
headers, body = responses[start[1]]
self.request.sendall(
b"HTTP/1.1 200 OK\r\nConnection: close\r\n" + headers + b"\r\n" + body
)
with TCPServer(("127.0.0.1", 0), Fixture) as server:
print(f"http://127.0.0.1:{server.server_address[1]}", flush=True)
server.serve_forever()
All three routes answer 200 OK and close the connection after the body. The third one is a control, it declares a Content-Length one byte larger than what it sends, which is a different kind of incomplete response, and it tells us whether the probe can see an incomplete response at all.
Asking URLSession
The app downloads with download(from:) so the probe tries that and bytes(from:) (I hoped the byte stream would throw where the file download didn’t) against each route, and compares the whole body with the expected bytes. bytes(from:) returns as soon as the response headers arrive, so we read the stream to the end inside the do block, otherwise an error in the body would never reach the catch.
import Foundation
guard CommandLine.arguments.count == 2,
let baseURL = URL(string: CommandLine.arguments[1]) else {
FileHandle.standardError.write(Data("Usage: swift Probe.swift <fixture-url>\n".utf8))
exit(2)
}
let expected = Data(repeating: 120, count: 100_000)
let session = URLSession(configuration: .ephemeral)
for name in ["complete", "missing-terminator", "short-length"] {
let url = baseURL.appending(path: name)
do {
let (file, response) = try await session.download(from: url)
defer { try? FileManager.default.removeItem(at: file) }
let body = try Data(contentsOf: file)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
print("download \(name) HTTP \(status) bytes=\(body.count) match=\(body == expected)")
} catch {
let error = error as NSError
print("download \(name) error=\(error.domain)/\(error.code)")
}
do {
let (stream, _) = try await session.bytes(from: url)
var body = Data()
for try await byte in stream {
body.append(byte)
}
print("bytes \(name) bytes=\(body.count) match=\(body == expected)")
} catch {
let error = error as NSError
print("bytes \(name) error=\(error.domain)/\(error.code)")
}
}
Save it as Probe.swift, start python3 fixture.py in one terminal, and run xcrun swift Probe.swift in another with the URL the fixture printed as its argument. Press Control-C in the first terminal when you’re done.
On macOS 26.7.3 (25G342) it prints:
download complete HTTP 200 bytes=100000 match=true
bytes complete bytes=100000 match=true
download missing-terminator HTTP 200 bytes=100000 match=true
bytes missing-terminator bytes=100000 match=true
download short-length error=NSURLErrorDomain/-1005
bytes short-length error=NSURLErrorDomain/-1005
The missing terminator makes no difference to either API, both return HTTP 200 and the full payload, while the short Content-Length fails with -1005 (NSURLErrorNetworkConnectionLost). So URLSession does notice when a body is shorter than its declared length, but not when a chunked body is never finished. My first idea in the app was to check the saved file instead, with a format parser or a known hash, which doesn’t help here at all (the file is correct, only the end of the message is missing).
The same responses with curl
curl reads the framing the way the RFC does, and with the fixture still running we can try all three routes:
for route in complete missing-terminator short-length; do
curl -s -o /dev/null "http://127.0.0.1:<port>/$route"
echo "$route exit=$?"
done
The complete response exits with 0, and the other two exit with 18, which is CURLE_PARTIAL_FILE. libcurl still passes all 100,000 bytes to its write callback for the missing terminator, it just doesn’t call the transfer a success afterwards.
Why the app kept URLSession
That made libcurl look like the fix, so I built a small signed probe that ran the same comparison inside an app on an iPad, on Mac Catalyst and in the iOS simulator, over HTTPS. libcurl caught the missing terminator there too, and URLSession again reported success for both chunked responses. I also gave both clients a server that only offers TLS 1.2 without forward secrecy, and there libcurl got HTTP 200 while URLSession refused with -1200, because App Transport Security requires forward secrecy. Moving the downloads to libcurl would have meant giving up ATS for every server the app talks to (and rebuilding its checks by hand), which is a bigger change than the bug it fixes.
In the end the app kept URLSession, the fixture and probe went to Apple as a Feedback report (FB25810905), and the issue in the app stays open until Foundation reports a chunked body that never finished.
So the paired responses are worth keeping for a download test, because they test the framing without the payload or its size giving anything away, but with URLSession that test can’t go red on a missing final chunk, since nothing in its API reports one. If an app needs to know that a chunked download really finished, that has to come from somewhere else, a length or hash the server publishes separately or a different HTTP client, and a different client has to be checked against more than this one bug (the ATS control is what ruled libcurl out for me). The short Content-Length route is still a cheap way to make sure the probe can see an incomplete response in the first place.