collector.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. """
  2. The main purpose of this module is to expose LinkCollector.collect_sources().
  3. """
  4. from __future__ import annotations
  5. import collections
  6. import email.message
  7. import functools
  8. import itertools
  9. import json
  10. import logging
  11. import os
  12. import urllib.parse
  13. from collections.abc import Iterable, MutableMapping, Sequence
  14. from dataclasses import dataclass
  15. from html.parser import HTMLParser
  16. from optparse import Values
  17. from typing import (
  18. Callable,
  19. NamedTuple,
  20. Protocol,
  21. )
  22. from pip._vendor import requests
  23. from pip._vendor.requests import Response
  24. from pip._vendor.requests.exceptions import RetryError, SSLError
  25. from pip._internal.exceptions import NetworkConnectionError
  26. from pip._internal.models.link import Link
  27. from pip._internal.models.search_scope import SearchScope
  28. from pip._internal.network.session import PipSession
  29. from pip._internal.network.utils import raise_for_status
  30. from pip._internal.utils.filetypes import is_archive_file
  31. from pip._internal.utils.misc import redact_auth_from_url
  32. from pip._internal.utils.urls import url_to_path
  33. from pip._internal.vcs import vcs
  34. from .sources import CandidatesFromPage, LinkSource, build_source
  35. logger = logging.getLogger(__name__)
  36. ResponseHeaders = MutableMapping[str, str]
  37. def _match_vcs_scheme(url: str) -> str | None:
  38. """Look for VCS schemes in the URL.
  39. Returns the matched VCS scheme, or None if there's no match.
  40. """
  41. for scheme in vcs.schemes:
  42. if url.lower().startswith(scheme) and url[len(scheme)] in "+:":
  43. return scheme
  44. return None
  45. class _NotAPIContent(Exception):
  46. def __init__(self, content_type: str, request_desc: str) -> None:
  47. super().__init__(content_type, request_desc)
  48. self.content_type = content_type
  49. self.request_desc = request_desc
  50. def _ensure_api_header(response: Response) -> None:
  51. """
  52. Check the Content-Type header to ensure the response contains a Simple
  53. API Response.
  54. Raises `_NotAPIContent` if the content type is not a valid content-type.
  55. """
  56. content_type = response.headers.get("Content-Type", "Unknown")
  57. content_type_l = content_type.lower()
  58. if content_type_l.startswith(
  59. (
  60. "text/html",
  61. "application/vnd.pypi.simple.v1+html",
  62. "application/vnd.pypi.simple.v1+json",
  63. )
  64. ):
  65. return
  66. raise _NotAPIContent(content_type, response.request.method)
  67. class _NotHTTP(Exception):
  68. pass
  69. def _ensure_api_response(url: str, session: PipSession) -> None:
  70. """
  71. Send a HEAD request to the URL, and ensure the response contains a simple
  72. API Response.
  73. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  74. `_NotAPIContent` if the content type is not a valid content type.
  75. """
  76. scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
  77. if scheme not in {"http", "https"}:
  78. raise _NotHTTP()
  79. resp = session.head(url, allow_redirects=True)
  80. raise_for_status(resp)
  81. _ensure_api_header(resp)
  82. def _get_simple_response(url: str, session: PipSession) -> Response:
  83. """Access an Simple API response with GET, and return the response.
  84. This consists of three parts:
  85. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  86. check the Content-Type is HTML or Simple API, to avoid downloading a
  87. large file. Raise `_NotHTTP` if the content type cannot be determined, or
  88. `_NotAPIContent` if it is not HTML or a Simple API.
  89. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  90. 3. Check the Content-Type header to make sure we got a Simple API response,
  91. and raise `_NotAPIContent` otherwise.
  92. """
  93. if is_archive_file(Link(url).filename):
  94. _ensure_api_response(url, session=session)
  95. logger.debug("Getting page %s", redact_auth_from_url(url))
  96. resp = session.get(
  97. url,
  98. headers={
  99. "Accept": ", ".join(
  100. [
  101. "application/vnd.pypi.simple.v1+json",
  102. "application/vnd.pypi.simple.v1+html; q=0.1",
  103. "text/html; q=0.01",
  104. ]
  105. ),
  106. # We don't want to blindly returned cached data for
  107. # /simple/, because authors generally expecting that
  108. # twine upload && pip install will function, but if
  109. # they've done a pip install in the last ~10 minutes
  110. # it won't. Thus by setting this to zero we will not
  111. # blindly use any cached data, however the benefit of
  112. # using max-age=0 instead of no-cache, is that we will
  113. # still support conditional requests, so we will still
  114. # minimize traffic sent in cases where the page hasn't
  115. # changed at all, we will just always incur the round
  116. # trip for the conditional GET now instead of only
  117. # once per 10 minutes.
  118. # For more information, please see pypa/pip#5670.
  119. "Cache-Control": "max-age=0",
  120. },
  121. )
  122. raise_for_status(resp)
  123. # The check for archives above only works if the url ends with
  124. # something that looks like an archive. However that is not a
  125. # requirement of an url. Unless we issue a HEAD request on every
  126. # url we cannot know ahead of time for sure if something is a
  127. # Simple API response or not. However we can check after we've
  128. # downloaded it.
  129. _ensure_api_header(resp)
  130. logger.debug(
  131. "Fetched page %s as %s",
  132. redact_auth_from_url(url),
  133. resp.headers.get("Content-Type", "Unknown"),
  134. )
  135. return resp
  136. def _get_encoding_from_headers(headers: ResponseHeaders) -> str | None:
  137. """Determine if we have any encoding information in our headers."""
  138. if headers and "Content-Type" in headers:
  139. m = email.message.Message()
  140. m["content-type"] = headers["Content-Type"]
  141. charset = m.get_param("charset")
  142. if charset:
  143. return str(charset)
  144. return None
  145. class CacheablePageContent:
  146. def __init__(self, page: IndexContent) -> None:
  147. assert page.cache_link_parsing
  148. self.page = page
  149. def __eq__(self, other: object) -> bool:
  150. return isinstance(other, type(self)) and self.page.url == other.page.url
  151. def __hash__(self) -> int:
  152. return hash(self.page.url)
  153. class ParseLinks(Protocol):
  154. def __call__(self, page: IndexContent) -> Iterable[Link]: ...
  155. def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
  156. """
  157. Given a function that parses an Iterable[Link] from an IndexContent, cache the
  158. function's result (keyed by CacheablePageContent), unless the IndexContent
  159. `page` has `page.cache_link_parsing == False`.
  160. """
  161. @functools.cache
  162. def wrapper(cacheable_page: CacheablePageContent) -> list[Link]:
  163. return list(fn(cacheable_page.page))
  164. @functools.wraps(fn)
  165. def wrapper_wrapper(page: IndexContent) -> list[Link]:
  166. if page.cache_link_parsing:
  167. return wrapper(CacheablePageContent(page))
  168. return list(fn(page))
  169. return wrapper_wrapper
  170. @with_cached_index_content
  171. def parse_links(page: IndexContent) -> Iterable[Link]:
  172. """
  173. Parse a Simple API's Index Content, and yield its anchor elements as Link objects.
  174. """
  175. content_type_l = page.content_type.lower()
  176. if content_type_l.startswith("application/vnd.pypi.simple.v1+json"):
  177. data = json.loads(page.content)
  178. for file in data.get("files", []):
  179. link = Link.from_json(file, page.url)
  180. if link is None:
  181. continue
  182. yield link
  183. return
  184. parser = HTMLLinkParser(page.url)
  185. encoding = page.encoding or "utf-8"
  186. parser.feed(page.content.decode(encoding))
  187. url = page.url
  188. base_url = parser.base_url or url
  189. for anchor in parser.anchors:
  190. link = Link.from_element(anchor, page_url=url, base_url=base_url)
  191. if link is None:
  192. continue
  193. yield link
  194. @dataclass(frozen=True)
  195. class IndexContent:
  196. """Represents one response (or page), along with its URL.
  197. :param encoding: the encoding to decode the given content.
  198. :param url: the URL from which the HTML was downloaded.
  199. :param cache_link_parsing: whether links parsed from this page's url
  200. should be cached. PyPI index urls should
  201. have this set to False, for example.
  202. """
  203. content: bytes
  204. content_type: str
  205. encoding: str | None
  206. url: str
  207. cache_link_parsing: bool = True
  208. def __str__(self) -> str:
  209. return redact_auth_from_url(self.url)
  210. class HTMLLinkParser(HTMLParser):
  211. """
  212. HTMLParser that keeps the first base HREF and a list of all anchor
  213. elements' attributes.
  214. """
  215. def __init__(self, url: str) -> None:
  216. super().__init__(convert_charrefs=True)
  217. self.url: str = url
  218. self.base_url: str | None = None
  219. self.anchors: list[dict[str, str | None]] = []
  220. def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
  221. if tag == "base" and self.base_url is None:
  222. href = self.get_href(attrs)
  223. if href is not None:
  224. self.base_url = href
  225. elif tag == "a":
  226. self.anchors.append(dict(attrs))
  227. def get_href(self, attrs: list[tuple[str, str | None]]) -> str | None:
  228. for name, value in attrs:
  229. if name == "href":
  230. return value
  231. return None
  232. def _handle_get_simple_fail(
  233. link: Link,
  234. reason: str | Exception,
  235. meth: Callable[..., None] | None = None,
  236. ) -> None:
  237. if meth is None:
  238. meth = logger.debug
  239. meth("Could not fetch URL %s: %s - skipping", link, reason)
  240. def _make_index_content(
  241. response: Response, cache_link_parsing: bool = True
  242. ) -> IndexContent:
  243. encoding = _get_encoding_from_headers(response.headers)
  244. return IndexContent(
  245. response.content,
  246. response.headers["Content-Type"],
  247. encoding=encoding,
  248. url=response.url,
  249. cache_link_parsing=cache_link_parsing,
  250. )
  251. def _get_index_content(link: Link, *, session: PipSession) -> IndexContent | None:
  252. url = link.url.split("#", 1)[0]
  253. # Check for VCS schemes that do not support lookup as web pages.
  254. vcs_scheme = _match_vcs_scheme(url)
  255. if vcs_scheme:
  256. logger.warning(
  257. "Cannot look at %s URL %s because it does not support lookup as web pages.",
  258. vcs_scheme,
  259. link,
  260. )
  261. return None
  262. # Tack index.html onto file:// URLs that point to directories
  263. if url.startswith("file:") and os.path.isdir(url_to_path(url)):
  264. # add trailing slash if not present so urljoin doesn't trim
  265. # final segment
  266. if not url.endswith("/"):
  267. url += "/"
  268. # TODO: In the future, it would be nice if pip supported PEP 691
  269. # style responses in the file:// URLs, however there's no
  270. # standard file extension for application/vnd.pypi.simple.v1+json
  271. # so we'll need to come up with something on our own.
  272. url = urllib.parse.urljoin(url, "index.html")
  273. logger.debug(" file: URL is directory, getting %s", url)
  274. try:
  275. resp = _get_simple_response(url, session=session)
  276. except _NotHTTP:
  277. logger.warning(
  278. "Skipping page %s because it looks like an archive, and cannot "
  279. "be checked by a HTTP HEAD request.",
  280. link,
  281. )
  282. except _NotAPIContent as exc:
  283. logger.warning(
  284. "Skipping page %s because the %s request got Content-Type: %s. "
  285. "The only supported Content-Types are application/vnd.pypi.simple.v1+json, "
  286. "application/vnd.pypi.simple.v1+html, and text/html",
  287. link,
  288. exc.request_desc,
  289. exc.content_type,
  290. )
  291. except NetworkConnectionError as exc:
  292. _handle_get_simple_fail(link, exc)
  293. except RetryError as exc:
  294. _handle_get_simple_fail(link, exc)
  295. except SSLError as exc:
  296. reason = "There was a problem confirming the ssl certificate: "
  297. reason += str(exc)
  298. _handle_get_simple_fail(link, reason, meth=logger.info)
  299. except requests.ConnectionError as exc:
  300. _handle_get_simple_fail(link, f"connection error: {exc}")
  301. except requests.Timeout:
  302. _handle_get_simple_fail(link, "timed out")
  303. else:
  304. return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing)
  305. return None
  306. class CollectedSources(NamedTuple):
  307. find_links: Sequence[LinkSource | None]
  308. index_urls: Sequence[LinkSource | None]
  309. class LinkCollector:
  310. """
  311. Responsible for collecting Link objects from all configured locations,
  312. making network requests as needed.
  313. The class's main method is its collect_sources() method.
  314. """
  315. def __init__(
  316. self,
  317. session: PipSession,
  318. search_scope: SearchScope,
  319. ) -> None:
  320. self.search_scope = search_scope
  321. self.session = session
  322. @classmethod
  323. def create(
  324. cls,
  325. session: PipSession,
  326. options: Values,
  327. suppress_no_index: bool = False,
  328. ) -> LinkCollector:
  329. """
  330. :param session: The Session to use to make requests.
  331. :param suppress_no_index: Whether to ignore the --no-index option
  332. when constructing the SearchScope object.
  333. """
  334. index_urls = [options.index_url] + options.extra_index_urls
  335. if options.no_index and not suppress_no_index:
  336. logger.debug(
  337. "Ignoring indexes: %s",
  338. ",".join(redact_auth_from_url(url) for url in index_urls),
  339. )
  340. index_urls = []
  341. # Make sure find_links is a list before passing to create().
  342. find_links = options.find_links or []
  343. search_scope = SearchScope.create(
  344. find_links=find_links,
  345. index_urls=index_urls,
  346. no_index=options.no_index,
  347. )
  348. link_collector = LinkCollector(
  349. session=session,
  350. search_scope=search_scope,
  351. )
  352. return link_collector
  353. @property
  354. def find_links(self) -> list[str]:
  355. return self.search_scope.find_links
  356. def fetch_response(self, location: Link) -> IndexContent | None:
  357. """
  358. Fetch an HTML page containing package links.
  359. """
  360. return _get_index_content(location, session=self.session)
  361. def collect_sources(
  362. self,
  363. project_name: str,
  364. candidates_from_page: CandidatesFromPage,
  365. ) -> CollectedSources:
  366. # The OrderedDict calls deduplicate sources by URL.
  367. index_url_sources = collections.OrderedDict(
  368. build_source(
  369. loc,
  370. candidates_from_page=candidates_from_page,
  371. page_validator=self.session.is_secure_origin,
  372. expand_dir=False,
  373. cache_link_parsing=False,
  374. project_name=project_name,
  375. )
  376. for loc in self.search_scope.get_index_urls_locations(project_name)
  377. ).values()
  378. find_links_sources = collections.OrderedDict(
  379. build_source(
  380. loc,
  381. candidates_from_page=candidates_from_page,
  382. page_validator=self.session.is_secure_origin,
  383. expand_dir=True,
  384. cache_link_parsing=True,
  385. project_name=project_name,
  386. )
  387. for loc in self.find_links
  388. ).values()
  389. if logger.isEnabledFor(logging.DEBUG):
  390. lines = [
  391. f"* {s.link}"
  392. for s in itertools.chain(find_links_sources, index_url_sources)
  393. if s is not None and s.link is not None
  394. ]
  395. lines = [
  396. f"{len(lines)} location(s) to search "
  397. f"for versions of {project_name}:"
  398. ] + lines
  399. logger.debug("\n".join(lines))
  400. return CollectedSources(
  401. find_links=list(find_links_sources),
  402. index_urls=list(index_url_sources),
  403. )