collector.py 16 KB

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