http.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import os
  2. import random
  3. import time
  4. from .common import FileDownloader
  5. from ..networking import Request
  6. from ..networking.exceptions import (
  7. CertificateVerifyError,
  8. HTTPError,
  9. TransportError,
  10. )
  11. from ..utils import (
  12. ContentTooShortError,
  13. RetryManager,
  14. ThrottledDownload,
  15. XAttrMetadataError,
  16. XAttrUnavailableError,
  17. int_or_none,
  18. parse_http_range,
  19. try_call,
  20. write_xattr,
  21. )
  22. from ..utils.networking import HTTPHeaderDict
  23. class HttpFD(FileDownloader):
  24. def real_download(self, filename, info_dict):
  25. url = info_dict['url']
  26. request_data = info_dict.get('request_data', None)
  27. class DownloadContext(dict):
  28. __getattr__ = dict.get
  29. __setattr__ = dict.__setitem__
  30. __delattr__ = dict.__delitem__
  31. ctx = DownloadContext()
  32. ctx.filename = filename
  33. ctx.tmpfilename = self.temp_name(filename)
  34. ctx.stream = None
  35. # Disable compression
  36. headers = HTTPHeaderDict({'Accept-Encoding': 'identity'}, info_dict.get('http_headers'))
  37. is_test = self.params.get('test', False)
  38. chunk_size = self._TEST_FILE_SIZE if is_test else (
  39. self.params.get('http_chunk_size')
  40. or info_dict.get('downloader_options', {}).get('http_chunk_size')
  41. or 0)
  42. ctx.open_mode = 'wb'
  43. ctx.resume_len = 0
  44. ctx.block_size = self.params.get('buffersize', 1024)
  45. ctx.start_time = time.time()
  46. # parse given Range
  47. req_start, req_end, _ = parse_http_range(headers.get('Range'))
  48. if self.params.get('continuedl', True):
  49. # Establish possible resume length
  50. if os.path.isfile(ctx.tmpfilename):
  51. ctx.resume_len = os.path.getsize(ctx.tmpfilename)
  52. ctx.is_resume = ctx.resume_len > 0
  53. class SucceedDownload(Exception):
  54. pass
  55. class RetryDownload(Exception):
  56. def __init__(self, source_error):
  57. self.source_error = source_error
  58. class NextFragment(Exception):
  59. pass
  60. def establish_connection():
  61. ctx.chunk_size = (random.randint(int(chunk_size * 0.95), chunk_size)
  62. if not is_test and chunk_size else chunk_size)
  63. if ctx.resume_len > 0:
  64. range_start = ctx.resume_len
  65. if req_start is not None:
  66. # offset the beginning of Range to be within request
  67. range_start += req_start
  68. if ctx.is_resume:
  69. self.report_resuming_byte(ctx.resume_len)
  70. ctx.open_mode = 'ab'
  71. elif req_start is not None:
  72. range_start = req_start
  73. elif ctx.chunk_size > 0:
  74. range_start = 0
  75. else:
  76. range_start = None
  77. ctx.is_resume = False
  78. if ctx.chunk_size:
  79. chunk_aware_end = range_start + ctx.chunk_size - 1
  80. # we're not allowed to download outside Range
  81. range_end = chunk_aware_end if req_end is None else min(chunk_aware_end, req_end)
  82. elif req_end is not None:
  83. # there's no need for chunked downloads, so download until the end of Range
  84. range_end = req_end
  85. else:
  86. range_end = None
  87. if try_call(lambda: range_start > range_end):
  88. ctx.resume_len = 0
  89. ctx.open_mode = 'wb'
  90. raise RetryDownload(Exception(f'Conflicting range. (start={range_start} > end={range_end})'))
  91. if try_call(lambda: range_end >= ctx.content_len):
  92. range_end = ctx.content_len - 1
  93. request = Request(url, request_data, headers)
  94. has_range = range_start is not None
  95. if has_range:
  96. request.headers['Range'] = f'bytes={int(range_start)}-{int_or_none(range_end) or ""}'
  97. # Establish connection
  98. try:
  99. ctx.data = self.ydl.urlopen(request)
  100. # When trying to resume, Content-Range HTTP header of response has to be checked
  101. # to match the value of requested Range HTTP header. This is due to a webservers
  102. # that don't support resuming and serve a whole file with no Content-Range
  103. # set in response despite of requested Range (see
  104. # https://github.com/ytdl-org/youtube-dl/issues/6057#issuecomment-126129799)
  105. if has_range:
  106. content_range = ctx.data.headers.get('Content-Range')
  107. content_range_start, content_range_end, content_len = parse_http_range(content_range)
  108. # Content-Range is present and matches requested Range, resume is possible
  109. if range_start == content_range_start and (
  110. # Non-chunked download
  111. not ctx.chunk_size
  112. # Chunked download and requested piece or
  113. # its part is promised to be served
  114. or content_range_end == range_end
  115. or content_len < range_end):
  116. ctx.content_len = content_len
  117. if content_len or req_end:
  118. ctx.data_len = min(content_len or req_end, req_end or content_len) - (req_start or 0)
  119. return
  120. # Content-Range is either not present or invalid. Assuming remote webserver is
  121. # trying to send the whole file, resume is not possible, so wiping the local file
  122. # and performing entire redownload
  123. elif range_start > 0:
  124. self.report_unable_to_resume()
  125. ctx.resume_len = 0
  126. ctx.open_mode = 'wb'
  127. ctx.data_len = ctx.content_len = int_or_none(ctx.data.headers.get('Content-length', None))
  128. except HTTPError as err:
  129. if err.status == 416:
  130. # Unable to resume (requested range not satisfiable)
  131. try:
  132. # Open the connection again without the range header
  133. ctx.data = self.ydl.urlopen(
  134. Request(url, request_data, headers))
  135. content_length = ctx.data.headers['Content-Length']
  136. except HTTPError as err:
  137. if err.status < 500 or err.status >= 600:
  138. raise
  139. else:
  140. # Examine the reported length
  141. if (content_length is not None
  142. and (ctx.resume_len - 100 < int(content_length) < ctx.resume_len + 100)):
  143. # The file had already been fully downloaded.
  144. # Explanation to the above condition: in issue #175 it was revealed that
  145. # YouTube sometimes adds or removes a few bytes from the end of the file,
  146. # changing the file size slightly and causing problems for some users. So
  147. # I decided to implement a suggested change and consider the file
  148. # completely downloaded if the file size differs less than 100 bytes from
  149. # the one in the hard drive.
  150. self.report_file_already_downloaded(ctx.filename)
  151. self.try_rename(ctx.tmpfilename, ctx.filename)
  152. self._hook_progress({
  153. 'filename': ctx.filename,
  154. 'status': 'finished',
  155. 'downloaded_bytes': ctx.resume_len,
  156. 'total_bytes': ctx.resume_len,
  157. }, info_dict)
  158. raise SucceedDownload
  159. else:
  160. # The length does not match, we start the download over
  161. self.report_unable_to_resume()
  162. ctx.resume_len = 0
  163. ctx.open_mode = 'wb'
  164. return
  165. elif err.status < 500 or err.status >= 600:
  166. # Unexpected HTTP error
  167. raise
  168. raise RetryDownload(err)
  169. except CertificateVerifyError:
  170. raise
  171. except TransportError as err:
  172. raise RetryDownload(err)
  173. def close_stream():
  174. if ctx.stream is not None:
  175. if ctx.tmpfilename != '-':
  176. ctx.stream.close()
  177. ctx.stream = None
  178. def download():
  179. data_len = ctx.data.headers.get('Content-length')
  180. if ctx.data.headers.get('Content-encoding'):
  181. # Content-encoding is present, Content-length is not reliable anymore as we are
  182. # doing auto decompression. (See: https://github.com/yt-dlp/yt-dlp/pull/6176)
  183. data_len = None
  184. # Range HTTP header may be ignored/unsupported by a webserver
  185. # (e.g. extractor/scivee.py, extractor/bambuser.py).
  186. # However, for a test we still would like to download just a piece of a file.
  187. # To achieve this we limit data_len to _TEST_FILE_SIZE and manually control
  188. # block size when downloading a file.
  189. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE):
  190. data_len = self._TEST_FILE_SIZE
  191. if data_len is not None:
  192. data_len = int(data_len) + ctx.resume_len
  193. min_data_len = self.params.get('min_filesize')
  194. max_data_len = self.params.get('max_filesize')
  195. if min_data_len is not None and data_len < min_data_len:
  196. self.to_screen(
  197. f'\r[download] File is smaller than min-filesize ({data_len} bytes < {min_data_len} bytes). Aborting.')
  198. return False
  199. if max_data_len is not None and data_len > max_data_len:
  200. self.to_screen(
  201. f'\r[download] File is larger than max-filesize ({data_len} bytes > {max_data_len} bytes). Aborting.')
  202. return False
  203. byte_counter = 0 + ctx.resume_len
  204. block_size = ctx.block_size
  205. start = time.time()
  206. # measure time over whole while-loop, so slow_down() and best_block_size() work together properly
  207. now = None # needed for slow_down() in the first loop run
  208. before = start # start measuring
  209. def retry(e):
  210. close_stream()
  211. if ctx.tmpfilename == '-':
  212. ctx.resume_len = byte_counter
  213. else:
  214. try:
  215. ctx.resume_len = os.path.getsize(ctx.tmpfilename)
  216. except FileNotFoundError:
  217. ctx.resume_len = 0
  218. raise RetryDownload(e)
  219. while True:
  220. try:
  221. # Download and write
  222. data_block = ctx.data.read(block_size if not is_test else min(block_size, data_len - byte_counter))
  223. except TransportError as err:
  224. retry(err)
  225. byte_counter += len(data_block)
  226. # exit loop when download is finished
  227. if len(data_block) == 0:
  228. break
  229. # Open destination file just in time
  230. if ctx.stream is None:
  231. try:
  232. ctx.stream, ctx.tmpfilename = self.sanitize_open(
  233. ctx.tmpfilename, ctx.open_mode)
  234. assert ctx.stream is not None
  235. ctx.filename = self.undo_temp_name(ctx.tmpfilename)
  236. self.report_destination(ctx.filename)
  237. except OSError as err:
  238. self.report_error(f'unable to open for writing: {err}')
  239. return False
  240. if self.params.get('xattr_set_filesize', False) and data_len is not None:
  241. try:
  242. write_xattr(ctx.tmpfilename, 'user.ytdl.filesize', str(data_len).encode())
  243. except (XAttrUnavailableError, XAttrMetadataError) as err:
  244. self.report_error(f'unable to set filesize xattr: {err}')
  245. try:
  246. ctx.stream.write(data_block)
  247. except OSError as err:
  248. self.to_stderr('\n')
  249. self.report_error(f'unable to write data: {err}')
  250. return False
  251. # Apply rate limit
  252. self.slow_down(start, now, byte_counter - ctx.resume_len)
  253. # end measuring of one loop run
  254. now = time.time()
  255. after = now
  256. # Adjust block size
  257. if not self.params.get('noresizebuffer', False):
  258. block_size = self.best_block_size(after - before, len(data_block))
  259. before = after
  260. # Progress message
  261. speed = self.calc_speed(start, now, byte_counter - ctx.resume_len)
  262. if ctx.data_len is None:
  263. eta = None
  264. else:
  265. eta = self.calc_eta(start, time.time(), ctx.data_len - ctx.resume_len, byte_counter - ctx.resume_len)
  266. self._hook_progress({
  267. 'status': 'downloading',
  268. 'downloaded_bytes': byte_counter,
  269. 'total_bytes': ctx.data_len,
  270. 'tmpfilename': ctx.tmpfilename,
  271. 'filename': ctx.filename,
  272. 'eta': eta,
  273. 'speed': speed,
  274. 'elapsed': now - ctx.start_time,
  275. 'ctx_id': info_dict.get('ctx_id'),
  276. }, info_dict)
  277. if data_len is not None and byte_counter == data_len:
  278. break
  279. if speed and speed < (self.params.get('throttledratelimit') or 0):
  280. # The speed must stay below the limit for 3 seconds
  281. # This prevents raising error when the speed temporarily goes down
  282. if ctx.throttle_start is None:
  283. ctx.throttle_start = now
  284. elif now - ctx.throttle_start > 3:
  285. if ctx.stream is not None and ctx.tmpfilename != '-':
  286. ctx.stream.close()
  287. raise ThrottledDownload
  288. elif speed:
  289. ctx.throttle_start = None
  290. if ctx.stream is None:
  291. self.to_stderr('\n')
  292. self.report_error('Did not get any data blocks')
  293. return False
  294. if not is_test and ctx.chunk_size and ctx.content_len is not None and byte_counter < ctx.content_len:
  295. ctx.resume_len = byte_counter
  296. raise NextFragment
  297. if ctx.tmpfilename != '-':
  298. ctx.stream.close()
  299. if data_len is not None and byte_counter != data_len:
  300. err = ContentTooShortError(byte_counter, int(data_len))
  301. retry(err)
  302. self.try_rename(ctx.tmpfilename, ctx.filename)
  303. # Update file modification time
  304. if self.params.get('updatetime', True):
  305. info_dict['filetime'] = self.try_utime(ctx.filename, ctx.data.headers.get('last-modified', None))
  306. self._hook_progress({
  307. 'downloaded_bytes': byte_counter,
  308. 'total_bytes': byte_counter,
  309. 'filename': ctx.filename,
  310. 'status': 'finished',
  311. 'elapsed': time.time() - ctx.start_time,
  312. 'ctx_id': info_dict.get('ctx_id'),
  313. }, info_dict)
  314. return True
  315. for retry in RetryManager(self.params.get('retries'), self.report_retry):
  316. try:
  317. establish_connection()
  318. return download()
  319. except RetryDownload as err:
  320. retry.error = err.source_error
  321. continue
  322. except NextFragment:
  323. retry.error = None
  324. retry.attempt -= 1
  325. continue
  326. except SucceedDownload:
  327. return True
  328. except: # noqa: E722
  329. close_stream()
  330. raise
  331. return False