collector.py 21 KB

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