1
0
mirror of https://github.com/yt-dlp/yt-dlp.git synced 2025-11-13 21:15:15 +00:00

[networking] Ensure underlying file object is closed when fully read (#14935)

Fixes https://github.com/yt-dlp/yt-dlp/issues/14891

Authored by: coletdjnz
This commit is contained in:
coletdjnz
2025-11-08 18:30:43 +13:00
committed by GitHub
parent 73fd850d17
commit 5767fb4ab1
5 changed files with 124 additions and 16 deletions

View File

@@ -306,7 +306,25 @@ class UrllibResponseAdapter(Response):
def read(self, amt=None):
try:
return self.fp.read(amt)
data = self.fp.read(amt)
underlying = getattr(self.fp, 'fp', None)
if isinstance(self.fp, http.client.HTTPResponse) and underlying is None:
# http.client.HTTPResponse automatically closes itself when fully read
self.close()
elif isinstance(self.fp, urllib.response.addinfourl) and underlying is not None:
# urllib's addinfourl does not close the underlying fp automatically when fully read
if isinstance(underlying, io.BytesIO):
# data URLs or in-memory responses (e.g. gzip/deflate/brotli decoded)
if underlying.tell() >= len(underlying.getbuffer()):
self.close()
elif isinstance(underlying, io.BufferedReader) and amt is None:
# file URLs.
# XXX: this will not mark the response as closed if it was fully read with amt.
self.close()
elif underlying is not None and underlying.closed:
# Catch-all for any cases where underlying file is closed
self.close()
return data
except Exception as e:
handle_response_read_exceptions(e)
raise e