collector.py 22 KB

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