download.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """Download files with progress indicators."""
  2. from __future__ import annotations
  3. import email.message
  4. import logging
  5. import mimetypes
  6. import os
  7. from collections.abc import Iterable, Mapping
  8. from dataclasses import dataclass
  9. from http import HTTPStatus
  10. from typing import BinaryIO
  11. from pip._vendor.requests import PreparedRequest
  12. from pip._vendor.requests.models import Response
  13. from pip._vendor.urllib3 import HTTPResponse as URLlib3Response
  14. from pip._vendor.urllib3._collections import HTTPHeaderDict
  15. from pip._vendor.urllib3.exceptions import ReadTimeoutError
  16. from pip._internal.cli.progress_bars import BarType, get_download_progress_renderer
  17. from pip._internal.exceptions import IncompleteDownloadError, NetworkConnectionError
  18. from pip._internal.models.index import PyPI
  19. from pip._internal.models.link import Link
  20. from pip._internal.network.cache import SafeFileCache, is_from_cache
  21. from pip._internal.network.session import CacheControlAdapter, PipSession
  22. from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
  23. from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
  24. logger = logging.getLogger(__name__)
  25. def _get_http_response_size(resp: Response) -> int | None:
  26. try:
  27. return int(resp.headers["content-length"])
  28. except (ValueError, KeyError, TypeError):
  29. return None
  30. def _get_http_response_etag_or_last_modified(resp: Response) -> str | None:
  31. """
  32. Return either the ETag or Last-Modified header (or None if neither exists).
  33. The return value can be used in an If-Range header.
  34. """
  35. return resp.headers.get("etag", resp.headers.get("last-modified"))
  36. def _log_download(
  37. resp: Response,
  38. link: Link,
  39. progress_bar: BarType,
  40. total_length: int | None,
  41. range_start: int | None = 0,
  42. ) -> Iterable[bytes]:
  43. if link.netloc == PyPI.file_storage_domain:
  44. url = link.show_url
  45. else:
  46. url = link.url_without_fragment
  47. logged_url = redact_auth_from_url(url)
  48. if total_length:
  49. if range_start:
  50. logged_url = (
  51. f"{logged_url} ({format_size(range_start)}/{format_size(total_length)})"
  52. )
  53. else:
  54. logged_url = f"{logged_url} ({format_size(total_length)})"
  55. if is_from_cache(resp):
  56. logger.info("Using cached %s", logged_url)
  57. elif range_start:
  58. logger.info("Resuming download %s", logged_url)
  59. else:
  60. logger.info("Downloading %s", logged_url)
  61. if logger.getEffectiveLevel() > logging.INFO:
  62. show_progress = False
  63. elif is_from_cache(resp):
  64. show_progress = False
  65. elif not total_length:
  66. show_progress = True
  67. elif total_length > (512 * 1024):
  68. show_progress = True
  69. else:
  70. show_progress = False
  71. chunks = response_chunks(resp)
  72. if not show_progress:
  73. return chunks
  74. renderer = get_download_progress_renderer(
  75. bar_type=progress_bar, size=total_length, initial_progress=range_start
  76. )
  77. return renderer(chunks)
  78. def sanitize_content_filename(filename: str) -> str:
  79. """
  80. Sanitize the "filename" value from a Content-Disposition header.
  81. """
  82. return os.path.basename(filename)
  83. def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
  84. """
  85. Parse the "filename" value from a Content-Disposition header, and
  86. return the default filename if the result is empty.
  87. """
  88. m = email.message.Message()
  89. m["content-type"] = content_disposition
  90. filename = m.get_param("filename")
  91. if filename:
  92. # We need to sanitize the filename to prevent directory traversal
  93. # in case the filename contains ".." path parts.
  94. filename = sanitize_content_filename(str(filename))
  95. return filename or default_filename
  96. def _get_http_response_filename(resp: Response, link: Link) -> str:
  97. """Get an ideal filename from the given HTTP response, falling back to
  98. the link filename if not provided.
  99. """
  100. filename = link.filename # fallback
  101. # Have a look at the Content-Disposition header for a better guess
  102. content_disposition = resp.headers.get("content-disposition")
  103. if content_disposition:
  104. filename = parse_content_disposition(content_disposition, filename)
  105. ext: str | None = splitext(filename)[1]
  106. if not ext:
  107. ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
  108. if ext:
  109. filename += ext
  110. if not ext and link.url != resp.url:
  111. ext = os.path.splitext(resp.url)[1]
  112. if ext:
  113. filename += ext
  114. return filename
  115. @dataclass
  116. class _FileDownload:
  117. """Stores the state of a single link download."""
  118. link: Link
  119. output_file: BinaryIO
  120. size: int | None
  121. bytes_received: int = 0
  122. reattempts: int = 0
  123. def is_incomplete(self) -> bool:
  124. return bool(self.size is not None and self.bytes_received < self.size)
  125. def write_chunk(self, data: bytes) -> None:
  126. self.bytes_received += len(data)
  127. self.output_file.write(data)
  128. def reset_file(self) -> None:
  129. """Delete any saved data and reset progress to zero."""
  130. self.output_file.seek(0)
  131. self.output_file.truncate()
  132. self.bytes_received = 0
  133. class Downloader:
  134. def __init__(
  135. self,
  136. session: PipSession,
  137. progress_bar: BarType,
  138. resume_retries: int,
  139. ) -> None:
  140. assert (
  141. resume_retries >= 0
  142. ), "Number of max resume retries must be bigger or equal to zero"
  143. self._session = session
  144. self._progress_bar = progress_bar
  145. self._resume_retries = resume_retries
  146. def batch(
  147. self, links: Iterable[Link], location: str
  148. ) -> Iterable[tuple[Link, tuple[str, str]]]:
  149. """Convenience method to download multiple links."""
  150. for link in links:
  151. filepath, content_type = self(link, location)
  152. yield link, (filepath, content_type)
  153. def __call__(self, link: Link, location: str) -> tuple[str, str]:
  154. """Download a link and save it under location."""
  155. resp = self._http_get(link)
  156. download_size = _get_http_response_size(resp)
  157. filepath = os.path.join(location, _get_http_response_filename(resp, link))
  158. with open(filepath, "wb") as content_file:
  159. download = _FileDownload(link, content_file, download_size)
  160. self._process_response(download, resp)
  161. if download.is_incomplete():
  162. self._attempt_resumes_or_redownloads(download, resp)
  163. content_type = resp.headers.get("Content-Type", "")
  164. return filepath, content_type
  165. def _process_response(self, download: _FileDownload, resp: Response) -> None:
  166. """Download and save chunks from a response."""
  167. chunks = _log_download(
  168. resp,
  169. download.link,
  170. self._progress_bar,
  171. download.size,
  172. range_start=download.bytes_received,
  173. )
  174. try:
  175. for chunk in chunks:
  176. download.write_chunk(chunk)
  177. except ReadTimeoutError as e:
  178. # If the download size is not known, then give up downloading the file.
  179. if download.size is None:
  180. raise e
  181. logger.warning("Connection timed out while downloading.")
  182. def _attempt_resumes_or_redownloads(
  183. self, download: _FileDownload, first_resp: Response
  184. ) -> None:
  185. """Attempt to resume/restart the download if connection was dropped."""
  186. while download.reattempts < self._resume_retries and download.is_incomplete():
  187. assert download.size is not None
  188. download.reattempts += 1
  189. logger.warning(
  190. "Attempting to resume incomplete download (%s/%s, attempt %d)",
  191. format_size(download.bytes_received),
  192. format_size(download.size),
  193. download.reattempts,
  194. )
  195. try:
  196. resume_resp = self._http_get_resume(download, should_match=first_resp)
  197. # Fallback: if the server responded with 200 (i.e., the file has
  198. # since been modified or range requests are unsupported) or any
  199. # other unexpected status, restart the download from the beginning.
  200. must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT
  201. if must_restart:
  202. download.reset_file()
  203. download.size = _get_http_response_size(resume_resp)
  204. first_resp = resume_resp
  205. self._process_response(download, resume_resp)
  206. except (ConnectionError, ReadTimeoutError, OSError):
  207. continue
  208. # No more resume attempts. Raise an error if the download is still incomplete.
  209. if download.is_incomplete():
  210. os.remove(download.output_file.name)
  211. raise IncompleteDownloadError(download)
  212. # If we successfully completed the download via resume, manually cache it
  213. # as a complete response to enable future caching
  214. if download.reattempts > 0:
  215. self._cache_resumed_download(download, first_resp)
  216. def _cache_resumed_download(
  217. self, download: _FileDownload, original_response: Response
  218. ) -> None:
  219. """
  220. Manually cache a file that was successfully downloaded via resume retries.
  221. cachecontrol doesn't cache 206 (Partial Content) responses, since they
  222. are not complete files. This method manually adds the final file to the
  223. cache as though it was downloaded in a single request, so that future
  224. requests can use the cache.
  225. """
  226. url = download.link.url_without_fragment
  227. adapter = self._session.get_adapter(url)
  228. # Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)
  229. if not isinstance(adapter, CacheControlAdapter):
  230. logger.debug(
  231. "Skipping resume download caching: no cache controller for %s", url
  232. )
  233. return
  234. # Check SafeFileCache is being used
  235. assert isinstance(
  236. adapter.cache, SafeFileCache
  237. ), "separate body cache not in use!"
  238. synthetic_request = PreparedRequest()
  239. synthetic_request.prepare(method="GET", url=url, headers={})
  240. synthetic_response_headers = HTTPHeaderDict()
  241. for key, value in original_response.headers.items():
  242. if key.lower() not in ["content-range", "content-length"]:
  243. synthetic_response_headers[key] = value
  244. synthetic_response_headers["content-length"] = str(download.size)
  245. synthetic_response = URLlib3Response(
  246. body="",
  247. headers=synthetic_response_headers,
  248. status=200,
  249. preload_content=False,
  250. )
  251. # Save metadata and then stream the file contents to cache.
  252. cache_url = adapter.controller.cache_url(url)
  253. metadata_blob = adapter.controller.serializer.dumps(
  254. synthetic_request, synthetic_response, b""
  255. )
  256. adapter.cache.set(cache_url, metadata_blob)
  257. download.output_file.flush()
  258. with open(download.output_file.name, "rb") as f:
  259. adapter.cache.set_body_from_io(cache_url, f)
  260. logger.debug(
  261. "Cached resumed download as complete response for future use: %s", url
  262. )
  263. def _http_get_resume(
  264. self, download: _FileDownload, should_match: Response
  265. ) -> Response:
  266. """Issue a HTTP range request to resume the download."""
  267. # To better understand the download resumption logic, see the mdn web docs:
  268. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests
  269. headers = HEADERS.copy()
  270. headers["Range"] = f"bytes={download.bytes_received}-"
  271. # If possible, use a conditional range request to avoid corrupted
  272. # downloads caused by the remote file changing in-between.
  273. if identifier := _get_http_response_etag_or_last_modified(should_match):
  274. headers["If-Range"] = identifier
  275. return self._http_get(download.link, headers)
  276. def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:
  277. target_url = link.url_without_fragment
  278. try:
  279. resp = self._session.get(target_url, headers=headers, stream=True)
  280. raise_for_status(resp)
  281. except NetworkConnectionError as e:
  282. assert e.response is not None
  283. logger.critical(
  284. "HTTP error %s while getting %s", e.response.status_code, link
  285. )
  286. raise
  287. return resp