collector.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. """
  2. The main purpose of this module is to expose LinkCollector.collect_sources().
  3. """
  4. import cgi
  5. import collections
  6. import functools
  7. import itertools
  8. import logging
  9. import os
  10. import re
  11. import urllib.parse
  12. import urllib.request
  13. import xml.etree.ElementTree
  14. from html.parser import HTMLParser
  15. from optparse import Values
  16. from typing import (
  17. TYPE_CHECKING,
  18. Callable,
  19. Dict,
  20. Iterable,
  21. List,
  22. MutableMapping,
  23. NamedTuple,
  24. Optional,
  25. Sequence,
  26. Tuple,
  27. Union,
  28. )
  29. from pip._vendor import html5lib, requests
  30. from pip._vendor.requests import Response
  31. from pip._vendor.requests.exceptions import RetryError, SSLError
  32. from pip._internal.exceptions import (
  33. BadHTMLDoctypeDeclaration,
  34. MissingHTMLDoctypeDeclaration,
  35. NetworkConnectionError,
  36. )
  37. from pip._internal.models.link import Link
  38. from pip._internal.models.search_scope import SearchScope
  39. from pip._internal.network.session import PipSession
  40. from pip._internal.network.utils import raise_for_status
  41. from pip._internal.utils.filetypes import is_archive_file
  42. from pip._internal.utils.misc import pairwise, redact_auth_from_url
  43. from pip._internal.vcs import vcs
  44. from .sources import CandidatesFromPage, LinkSource, build_source
  45. if TYPE_CHECKING:
  46. from typing import Protocol
  47. else:
  48. Protocol = object
  49. logger = logging.getLogger(__name__)
  50. HTMLElement = xml.etree.ElementTree.Element
  51. ResponseHeaders = MutableMapping[str, str]
  52. def _match_vcs_scheme(url: str) -> Optional[str]:
  53. """Look for VCS schemes in the URL.
  54. Returns the matched VCS scheme, or None if there's no match.
  55. """
  56. for scheme in vcs.schemes:
  57. if url.lower().startswith(scheme) and url[len(scheme)] in "+:":
  58. return scheme
  59. return None
  60. class _NotHTML(Exception):
  61. def __init__(self, content_type: str, request_desc: str) -> None:
  62. super().__init__(content_type, request_desc)
  63. self.content_type = content_type
  64. self.request_desc = request_desc
  65. def _ensure_html_header(response: Response) -> None:
  66. """Check the Content-Type header to ensure the response contains HTML.
  67. Raises `_NotHTML` if the content type is not text/html.
  68. """
  69. content_type = response.headers.get("Content-Type", "")
  70. if not content_type.lower().startswith("text/html"):
  71. raise _NotHTML(content_type, response.request.method)
  72. class _NotHTTP(Exception):
  73. pass
  74. def _ensure_html_response(url: str, session: PipSession) -> None:
  75. """Send a HEAD request to the URL, and ensure the response contains HTML.
  76. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  77. `_NotHTML` if the content type is not text/html.
  78. """
  79. scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
  80. if scheme not in {"http", "https"}:
  81. raise _NotHTTP()
  82. resp = session.head(url, allow_redirects=True)
  83. raise_for_status(resp)
  84. _ensure_html_header(resp)
  85. def _get_html_response(url: str, session: PipSession) -> Response:
  86. """Access an HTML page with GET, and return the response.
  87. This consists of three parts:
  88. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  89. check the Content-Type is HTML, to avoid downloading a large file.
  90. Raise `_NotHTTP` if the content type cannot be determined, or
  91. `_NotHTML` if it is not HTML.
  92. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  93. 3. Check the Content-Type header to make sure we got HTML, and raise
  94. `_NotHTML` otherwise.
  95. """
  96. if is_archive_file(Link(url).filename):
  97. _ensure_html_response(url, session=session)
  98. logger.debug("Getting page %s", redact_auth_from_url(url))
  99. resp = session.get(
  100. url,
  101. headers={
  102. "Accept": "text/html",
  103. # We don't want to blindly returned cached data for
  104. # /simple/, because authors generally expecting that
  105. # twine upload && pip install will function, but if
  106. # they've done a pip install in the last ~10 minutes
  107. # it won't. Thus by setting this to zero we will not
  108. # blindly use any cached data, however the benefit of
  109. # using max-age=0 instead of no-cache, is that we will
  110. # still support conditional requests, so we will still
  111. # minimize traffic sent in cases where the page hasn't
  112. # changed at all, we will just always incur the round
  113. # trip for the conditional GET now instead of only
  114. # once per 10 minutes.
  115. # For more information, please see pypa/pip#5670.
  116. "Cache-Control": "max-age=0",
  117. },
  118. )
  119. raise_for_status(resp)
  120. # The check for archives above only works if the url ends with
  121. # something that looks like an archive. However that is not a
  122. # requirement of an url. Unless we issue a HEAD request on every
  123. # url we cannot know ahead of time for sure if something is HTML
  124. # or not. However we can check after we've downloaded it.
  125. _ensure_html_header(resp)
  126. return resp
  127. def _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]:
  128. """Determine if we have any encoding information in our headers."""
  129. if headers and "Content-Type" in headers:
  130. content_type, params = cgi.parse_header(headers["Content-Type"])
  131. if "charset" in params:
  132. return params["charset"]
  133. return None
  134. def _determine_base_url(document: HTMLElement, page_url: str) -> str:
  135. """Determine the HTML document's base URL.
  136. This looks for a ``<base>`` tag in the HTML document. If present, its href
  137. attribute denotes the base URL of anchor tags in the document. If there is
  138. no such tag (or if it does not have a valid href attribute), the HTML
  139. file's URL is used as the base URL.
  140. :param document: An HTML document representation. The current
  141. implementation expects the result of ``html5lib.parse()``.
  142. :param page_url: The URL of the HTML document.
  143. TODO: Remove when `html5lib` is dropped.
  144. """
  145. for base in document.findall(".//base"):
  146. href = base.get("href")
  147. if href is not None:
  148. return href
  149. return page_url
  150. def _clean_url_path_part(part: str) -> str:
  151. """
  152. Clean a "part" of a URL path (i.e. after splitting on "@" characters).
  153. """
  154. # We unquote prior to quoting to make sure nothing is double quoted.
  155. return urllib.parse.quote(urllib.parse.unquote(part))
  156. def _clean_file_url_path(part: str) -> str:
  157. """
  158. Clean the first part of a URL path that corresponds to a local
  159. filesystem path (i.e. the first part after splitting on "@" characters).
  160. """
  161. # We unquote prior to quoting to make sure nothing is double quoted.
  162. # Also, on Windows the path part might contain a drive letter which
  163. # should not be quoted. On Linux where drive letters do not
  164. # exist, the colon should be quoted. We rely on urllib.request
  165. # to do the right thing here.
  166. return urllib.request.pathname2url(urllib.request.url2pathname(part))
  167. # percent-encoded: /
  168. _reserved_chars_re = re.compile("(@|%2F)", re.IGNORECASE)
  169. def _clean_url_path(path: str, is_local_path: bool) -> str:
  170. """
  171. Clean the path portion of a URL.
  172. """
  173. if is_local_path:
  174. clean_func = _clean_file_url_path
  175. else:
  176. clean_func = _clean_url_path_part
  177. # Split on the reserved characters prior to cleaning so that
  178. # revision strings in VCS URLs are properly preserved.
  179. parts = _reserved_chars_re.split(path)
  180. cleaned_parts = []
  181. for to_clean, reserved in pairwise(itertools.chain(parts, [""])):
  182. cleaned_parts.append(clean_func(to_clean))
  183. # Normalize %xx escapes (e.g. %2f -> %2F)
  184. cleaned_parts.append(reserved.upper())
  185. return "".join(cleaned_parts)
  186. def _clean_link(url: str) -> str:
  187. """
  188. Make sure a link is fully quoted.
  189. For example, if ' ' occurs in the URL, it will be replaced with "%20",
  190. and without double-quoting other characters.
  191. """
  192. # Split the URL into parts according to the general structure
  193. # `scheme://netloc/path;parameters?query#fragment`.
  194. result = urllib.parse.urlparse(url)
  195. # If the netloc is empty, then the URL refers to a local filesystem path.
  196. is_local_path = not result.netloc
  197. path = _clean_url_path(result.path, is_local_path=is_local_path)
  198. return urllib.parse.urlunparse(result._replace(path=path))
  199. def _create_link_from_element(
  200. element_attribs: Dict[str, Optional[str]],
  201. page_url: str,
  202. base_url: str,
  203. ) -> Optional[Link]:
  204. """
  205. Convert an anchor element's attributes in a simple repository page to a Link.
  206. """
  207. href = element_attribs.get("href")
  208. if not href:
  209. return None
  210. url = _clean_link(urllib.parse.urljoin(base_url, href))
  211. pyrequire = element_attribs.get("data-requires-python")
  212. yanked_reason = element_attribs.get("data-yanked")
  213. link = Link(
  214. url,
  215. comes_from=page_url,
  216. requires_python=pyrequire,
  217. yanked_reason=yanked_reason,
  218. )
  219. return link
  220. class CacheablePageContent:
  221. def __init__(self, page: "HTMLPage") -> None:
  222. assert page.cache_link_parsing
  223. self.page = page
  224. def __eq__(self, other: object) -> bool:
  225. return isinstance(other, type(self)) and self.page.url == other.page.url
  226. def __hash__(self) -> int:
  227. return hash(self.page.url)
  228. class ParseLinks(Protocol):
  229. def __call__(
  230. self, page: "HTMLPage", use_deprecated_html5lib: bool
  231. ) -> Iterable[Link]:
  232. ...
  233. def with_cached_html_pages(fn: ParseLinks) -> ParseLinks:
  234. """
  235. Given a function that parses an Iterable[Link] from an HTMLPage, cache the
  236. function's result (keyed by CacheablePageContent), unless the HTMLPage
  237. `page` has `page.cache_link_parsing == False`.
  238. """
  239. @functools.lru_cache(maxsize=None)
  240. def wrapper(
  241. cacheable_page: CacheablePageContent, use_deprecated_html5lib: bool
  242. ) -> List[Link]:
  243. return list(fn(cacheable_page.page, use_deprecated_html5lib))
  244. @functools.wraps(fn)
  245. def wrapper_wrapper(page: "HTMLPage", use_deprecated_html5lib: bool) -> List[Link]:
  246. if page.cache_link_parsing:
  247. return wrapper(CacheablePageContent(page), use_deprecated_html5lib)
  248. return list(fn(page, use_deprecated_html5lib))
  249. return wrapper_wrapper
  250. def _parse_links_html5lib(page: "HTMLPage") -> Iterable[Link]:
  251. """
  252. Parse an HTML document, and yield its anchor elements as Link objects.
  253. TODO: Remove when `html5lib` is dropped.
  254. """
  255. document = html5lib.parse(
  256. page.content,
  257. transport_encoding=page.encoding,
  258. namespaceHTMLElements=False,
  259. )
  260. url = page.url
  261. base_url = _determine_base_url(document, url)
  262. for anchor in document.findall(".//a"):
  263. link = _create_link_from_element(
  264. anchor.attrib,
  265. page_url=url,
  266. base_url=base_url,
  267. )
  268. if link is None:
  269. continue
  270. yield link
  271. @with_cached_html_pages
  272. def parse_links(page: "HTMLPage", use_deprecated_html5lib: bool) -> Iterable[Link]:
  273. """
  274. Parse an HTML document, and yield its anchor elements as Link objects.
  275. """
  276. if use_deprecated_html5lib:
  277. yield from _parse_links_html5lib(page)
  278. return
  279. parser = HTMLLinkParser(page.url)
  280. encoding = page.encoding or "utf-8"
  281. parser.feed(page.content.decode(encoding))
  282. url = page.url
  283. base_url = parser.base_url or url
  284. for anchor in parser.anchors:
  285. link = _create_link_from_element(
  286. anchor,
  287. page_url=url,
  288. base_url=base_url,
  289. )
  290. if link is None:
  291. continue
  292. yield link
  293. class HTMLPage:
  294. """Represents one page, along with its URL"""
  295. def __init__(
  296. self,
  297. content: bytes,
  298. encoding: Optional[str],
  299. url: str,
  300. cache_link_parsing: bool = True,
  301. ) -> None:
  302. """
  303. :param encoding: the encoding to decode the given content.
  304. :param url: the URL from which the HTML was downloaded.
  305. :param cache_link_parsing: whether links parsed from this page's url
  306. should be cached. PyPI index urls should
  307. have this set to False, for example.
  308. """
  309. self.content = content
  310. self.encoding = encoding
  311. self.url = url
  312. self.cache_link_parsing = cache_link_parsing
  313. def __str__(self) -> str:
  314. return redact_auth_from_url(self.url)
  315. class HTMLLinkParser(HTMLParser):
  316. """
  317. HTMLParser that keeps the first base HREF and a list of all anchor
  318. elements' attributes.
  319. """
  320. def __init__(self, url: str) -> None:
  321. super().__init__(convert_charrefs=True)
  322. self._dealt_with_doctype_issues = False
  323. self.url: str = url
  324. self.base_url: Optional[str] = None
  325. self.anchors: List[Dict[str, Optional[str]]] = []
  326. def handle_decl(self, decl: str) -> None:
  327. self._dealt_with_doctype_issues = True
  328. match = re.match(
  329. r"""doctype\s+html\s*(?:SYSTEM\s+(["'])about:legacy-compat\1)?\s*$""",
  330. decl,
  331. re.IGNORECASE,
  332. )
  333. if match is None:
  334. logger.warning(
  335. "[present-diagnostic] %s",
  336. BadHTMLDoctypeDeclaration(url=self.url),
  337. )
  338. def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
  339. if not self._dealt_with_doctype_issues:
  340. logger.warning(
  341. "[present-diagnostic] %s",
  342. MissingHTMLDoctypeDeclaration(url=self.url),
  343. )
  344. self._dealt_with_doctype_issues = True
  345. if tag == "base" and self.base_url is None:
  346. href = self.get_href(attrs)
  347. if href is not None:
  348. self.base_url = href
  349. elif tag == "a":
  350. self.anchors.append(dict(attrs))
  351. def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]:
  352. for name, value in attrs:
  353. if name == "href":
  354. return value
  355. return None
  356. def _handle_get_page_fail(
  357. link: Link,
  358. reason: Union[str, Exception],
  359. meth: Optional[Callable[..., None]] = None,
  360. ) -> None:
  361. if meth is None:
  362. meth = logger.debug
  363. meth("Could not fetch URL %s: %s - skipping", link, reason)
  364. def _make_html_page(response: Response, cache_link_parsing: bool = True) -> HTMLPage:
  365. encoding = _get_encoding_from_headers(response.headers)
  366. return HTMLPage(
  367. response.content,
  368. encoding=encoding,
  369. url=response.url,
  370. cache_link_parsing=cache_link_parsing,
  371. )
  372. def _get_html_page(
  373. link: Link, session: Optional[PipSession] = None
  374. ) -> Optional["HTMLPage"]:
  375. if session is None:
  376. raise TypeError(
  377. "_get_html_page() missing 1 required keyword argument: 'session'"
  378. )
  379. url = link.url.split("#", 1)[0]
  380. # Check for VCS schemes that do not support lookup as web pages.
  381. vcs_scheme = _match_vcs_scheme(url)
  382. if vcs_scheme:
  383. logger.warning(
  384. "Cannot look at %s URL %s because it does not support lookup as web pages.",
  385. vcs_scheme,
  386. link,
  387. )
  388. return None
  389. # Tack index.html onto file:// URLs that point to directories
  390. scheme, _, path, _, _, _ = urllib.parse.urlparse(url)
  391. if scheme == "file" and os.path.isdir(urllib.request.url2pathname(path)):
  392. # add trailing slash if not present so urljoin doesn't trim
  393. # final segment
  394. if not url.endswith("/"):
  395. url += "/"
  396. url = urllib.parse.urljoin(url, "index.html")
  397. logger.debug(" file: URL is directory, getting %s", url)
  398. try:
  399. resp = _get_html_response(url, session=session)
  400. except _NotHTTP:
  401. logger.warning(
  402. "Skipping page %s because it looks like an archive, and cannot "
  403. "be checked by a HTTP HEAD request.",
  404. link,
  405. )
  406. except _NotHTML as exc:
  407. logger.warning(
  408. "Skipping page %s because the %s request got Content-Type: %s."
  409. "The only supported Content-Type is text/html",
  410. link,
  411. exc.request_desc,
  412. exc.content_type,
  413. )
  414. except NetworkConnectionError as exc:
  415. _handle_get_page_fail(link, exc)
  416. except RetryError as exc:
  417. _handle_get_page_fail(link, exc)
  418. except SSLError as exc:
  419. reason = "There was a problem confirming the ssl certificate: "
  420. reason += str(exc)
  421. _handle_get_page_fail(link, reason, meth=logger.info)
  422. except requests.ConnectionError as exc:
  423. _handle_get_page_fail(link, f"connection error: {exc}")
  424. except requests.Timeout:
  425. _handle_get_page_fail(link, "timed out")
  426. else:
  427. return _make_html_page(resp, cache_link_parsing=link.cache_link_parsing)
  428. return None
  429. class CollectedSources(NamedTuple):
  430. find_links: Sequence[Optional[LinkSource]]
  431. index_urls: Sequence[Optional[LinkSource]]
  432. class LinkCollector:
  433. """
  434. Responsible for collecting Link objects from all configured locations,
  435. making network requests as needed.
  436. The class's main method is its collect_sources() method.
  437. """
  438. def __init__(
  439. self,
  440. session: PipSession,
  441. search_scope: SearchScope,
  442. ) -> None:
  443. self.search_scope = search_scope
  444. self.session = session
  445. @classmethod
  446. def create(
  447. cls,
  448. session: PipSession,
  449. options: Values,
  450. suppress_no_index: bool = False,
  451. ) -> "LinkCollector":
  452. """
  453. :param session: The Session to use to make requests.
  454. :param suppress_no_index: Whether to ignore the --no-index option
  455. when constructing the SearchScope object.
  456. """
  457. index_urls = [options.index_url] + options.extra_index_urls
  458. if options.no_index and not suppress_no_index:
  459. logger.debug(
  460. "Ignoring indexes: %s",
  461. ",".join(redact_auth_from_url(url) for url in index_urls),
  462. )
  463. index_urls = []
  464. # Make sure find_links is a list before passing to create().
  465. find_links = options.find_links or []
  466. search_scope = SearchScope.create(
  467. find_links=find_links,
  468. index_urls=index_urls,
  469. )
  470. link_collector = LinkCollector(
  471. session=session,
  472. search_scope=search_scope,
  473. )
  474. return link_collector
  475. @property
  476. def find_links(self) -> List[str]:
  477. return self.search_scope.find_links
  478. def fetch_page(self, location: Link) -> Optional[HTMLPage]:
  479. """
  480. Fetch an HTML page containing package links.
  481. """
  482. return _get_html_page(location, session=self.session)
  483. def collect_sources(
  484. self,
  485. project_name: str,
  486. candidates_from_page: CandidatesFromPage,
  487. ) -> CollectedSources:
  488. # The OrderedDict calls deduplicate sources by URL.
  489. index_url_sources = collections.OrderedDict(
  490. build_source(
  491. loc,
  492. candidates_from_page=candidates_from_page,
  493. page_validator=self.session.is_secure_origin,
  494. expand_dir=False,
  495. cache_link_parsing=False,
  496. )
  497. for loc in self.search_scope.get_index_urls_locations(project_name)
  498. ).values()
  499. find_links_sources = collections.OrderedDict(
  500. build_source(
  501. loc,
  502. candidates_from_page=candidates_from_page,
  503. page_validator=self.session.is_secure_origin,
  504. expand_dir=True,
  505. cache_link_parsing=True,
  506. )
  507. for loc in self.find_links
  508. ).values()
  509. if logger.isEnabledFor(logging.DEBUG):
  510. lines = [
  511. f"* {s.link}"
  512. for s in itertools.chain(find_links_sources, index_url_sources)
  513. if s is not None and s.link is not None
  514. ]
  515. lines = [
  516. f"{len(lines)} location(s) to search "
  517. f"for versions of {project_name}:"
  518. ] + lines
  519. logger.debug("\n".join(lines))
  520. return CollectedSources(
  521. find_links=list(find_links_sources),
  522. index_urls=list(index_url_sources),
  523. )