collector.py 17 KB

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