download.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. ) -> None:
  139. self._session = session
  140. self._progress_bar = progress_bar
  141. self._resume_retries = session.resume_retries
  142. assert (
  143. self._resume_retries >= 0
  144. ), "Number of max resume retries must be bigger or equal to zero"
  145. def batch(
  146. self, links: Iterable[Link], location: str
  147. ) -> Iterable[tuple[Link, tuple[str, str]]]:
  148. """Convenience method to download multiple links."""
  149. for link in links:
  150. filepath, content_type = self(link, location)
  151. yield link, (filepath, content_type)
  152. def __call__(self, link: Link, location: str) -> tuple[str, str]:
  153. """Download a link and save it under location."""
  154. resp = self._http_get(link)
  155. download_size = _get_http_response_size(resp)
  156. filepath = os.path.join(location, _get_http_response_filename(resp, link))
  157. with open(filepath, "wb") as content_file:
  158. download = _FileDownload(link, content_file, download_size)
  159. self._process_response(download, resp)
  160. if download.is_incomplete():
  161. self._attempt_resumes_or_redownloads(download, resp)
  162. content_type = resp.headers.get("Content-Type", "")
  163. return filepath, content_type
  164. def _process_response(self, download: _FileDownload, resp: Response) -> None:
  165. """Download and save chunks from a response."""
  166. chunks = _log_download(
  167. resp,
  168. download.link,
  169. self._progress_bar,
  170. download.size,
  171. range_start=download.bytes_received,
  172. )
  173. try:
  174. for chunk in chunks:
  175. download.write_chunk(chunk)
  176. except ReadTimeoutError as e:
  177. # If the download size is not known, then give up downloading the file.
  178. if download.size is None:
  179. raise e
  180. logger.warning("Connection timed out while downloading.")
  181. def _attempt_resumes_or_redownloads(
  182. self, download: _FileDownload, first_resp: Response
  183. ) -> None:
  184. """Attempt to resume/restart the download if connection was dropped."""
  185. while download.reattempts < self._resume_retries and download.is_incomplete():
  186. assert download.size is not None
  187. download.reattempts += 1
  188. logger.warning(
  189. "Attempting to resume incomplete download (%s/%s, attempt %d)",
  190. format_size(download.bytes_received),
  191. format_size(download.size),
  192. download.reattempts,
  193. )
  194. try:
  195. resume_resp = self._http_get_resume(download, should_match=first_resp)
  196. # Fallback: if the server responded with 200 (i.e., the file has
  197. # since been modified or range requests are unsupported) or any
  198. # other unexpected status, restart the download from the beginning.
  199. must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT
  200. if must_restart:
  201. download.reset_file()
  202. download.size = _get_http_response_size(resume_resp)
  203. first_resp = resume_resp
  204. self._process_response(download, resume_resp)
  205. except (ConnectionError, ReadTimeoutError, OSError):
  206. continue
  207. # No more resume attempts. Raise an error if the download is still incomplete.
  208. if download.is_incomplete():
  209. os.remove(download.output_file.name)
  210. raise IncompleteDownloadError(download)
  211. # If we successfully completed the download via resume, manually cache it
  212. # as a complete response to enable future caching
  213. if download.reattempts > 0:
  214. self._cache_resumed_download(download, first_resp)
  215. def _cache_resumed_download(
  216. self, download: _FileDownload, original_response: Response
  217. ) -> None:
  218. """
  219. Manually cache a file that was successfully downloaded via resume retries.
  220. cachecontrol doesn't cache 206 (Partial Content) responses, since they
  221. are not complete files. This method manually adds the final file to the
  222. cache as though it was downloaded in a single request, so that future
  223. requests can use the cache.
  224. """
  225. url = download.link.url_without_fragment
  226. adapter = self._session.get_adapter(url)
  227. # Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)
  228. if not isinstance(adapter, CacheControlAdapter):
  229. logger.debug(
  230. "Skipping resume download caching: no cache controller for %s", url
  231. )
  232. return
  233. # Check SafeFileCache is being used
  234. assert isinstance(
  235. adapter.cache, SafeFileCache
  236. ), "separate body cache not in use!"
  237. synthetic_request = PreparedRequest()
  238. synthetic_request.prepare(method="GET", url=url, headers={})
  239. synthetic_response_headers = HTTPHeaderDict()
  240. for key, value in original_response.headers.items():
  241. if key.lower() not in ["content-range", "content-length"]:
  242. synthetic_response_headers[key] = value
  243. synthetic_response_headers["content-length"] = str(download.size)
  244. synthetic_response = URLlib3Response(
  245. body="",
  246. headers=synthetic_response_headers,
  247. status=200,
  248. preload_content=False,
  249. )
  250. # Save metadata and then stream the file contents to cache.
  251. cache_url = adapter.controller.cache_url(url)
  252. metadata_blob = adapter.controller.serializer.dumps(
  253. synthetic_request, synthetic_response, b""
  254. )
  255. adapter.cache.set(cache_url, metadata_blob)
  256. download.output_file.flush()
  257. with open(download.output_file.name, "rb") as f:
  258. adapter.cache.set_body_from_io(cache_url, f)
  259. logger.debug(
  260. "Cached resumed download as complete response for future use: %s", url
  261. )
  262. def _http_get_resume(
  263. self, download: _FileDownload, should_match: Response
  264. ) -> Response:
  265. """Issue a HTTP range request to resume the download."""
  266. # To better understand the download resumption logic, see the mdn web docs:
  267. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests
  268. headers = HEADERS.copy()
  269. headers["Range"] = f"bytes={download.bytes_received}-"
  270. # If possible, use a conditional range request to avoid corrupted
  271. # downloads caused by the remote file changing in-between.
  272. if identifier := _get_http_response_etag_or_last_modified(should_match):
  273. headers["If-Range"] = identifier
  274. return self._http_get(download.link, headers)
  275. def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:
  276. target_url = link.url_without_fragment
  277. try:
  278. resp = self._session.get(target_url, headers=headers, stream=True)
  279. raise_for_status(resp)
  280. except NetworkConnectionError as e:
  281. assert e.response is not None
  282. logger.critical(
  283. "HTTP error %s while getting %s", e.response.status_code, link
  284. )
  285. raise
  286. return resp