You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

collector.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. """
  2. The main purpose of this module is to expose LinkCollector.collect_links().
  3. """
  4. # The following comment should be removed at some point in the future.
  5. # mypy: disallow-untyped-defs=False
  6. import cgi
  7. import itertools
  8. import logging
  9. import mimetypes
  10. import os
  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 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, Dict, Iterable, List, MutableMapping, Optional, Sequence,
  26. Tuple, 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. logger = logging.getLogger(__name__)
  35. def _match_vcs_scheme(url):
  36. # type: (str) -> Optional[str]
  37. """Look for VCS schemes in the URL.
  38. Returns the matched VCS scheme, or None if there's no match.
  39. """
  40. for scheme in vcs.schemes:
  41. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  42. return scheme
  43. return None
  44. def _is_url_like_archive(url):
  45. # type: (str) -> bool
  46. """Return whether the URL looks like an archive.
  47. """
  48. filename = Link(url).filename
  49. for bad_ext in ARCHIVE_EXTENSIONS:
  50. if filename.endswith(bad_ext):
  51. return True
  52. return False
  53. class _NotHTML(Exception):
  54. def __init__(self, content_type, request_desc):
  55. # type: (str, str) -> None
  56. super(_NotHTML, self).__init__(content_type, request_desc)
  57. self.content_type = content_type
  58. self.request_desc = request_desc
  59. def _ensure_html_header(response):
  60. # type: (Response) -> None
  61. """Check the Content-Type header to ensure the response contains HTML.
  62. Raises `_NotHTML` if the content type is not text/html.
  63. """
  64. content_type = response.headers.get("Content-Type", "")
  65. if not content_type.lower().startswith("text/html"):
  66. raise _NotHTML(content_type, response.request.method)
  67. class _NotHTTP(Exception):
  68. pass
  69. def _ensure_html_response(url, session):
  70. # type: (str, PipSession) -> None
  71. """Send a HEAD request to the URL, and ensure the response contains HTML.
  72. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  73. `_NotHTML` if the content type is not text/html.
  74. """
  75. scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
  76. if scheme not in {'http', 'https'}:
  77. raise _NotHTTP()
  78. resp = session.head(url, allow_redirects=True)
  79. resp.raise_for_status()
  80. _ensure_html_header(resp)
  81. def _get_html_response(url, session):
  82. # type: (str, PipSession) -> Response
  83. """Access an HTML page with GET, and return the response.
  84. This consists of three parts:
  85. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  86. check the Content-Type is HTML, to avoid downloading a large file.
  87. Raise `_NotHTTP` if the content type cannot be determined, or
  88. `_NotHTML` if it is not HTML.
  89. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  90. 3. Check the Content-Type header to make sure we got HTML, and raise
  91. `_NotHTML` otherwise.
  92. """
  93. if _is_url_like_archive(url):
  94. _ensure_html_response(url, session=session)
  95. logger.debug('Getting page %s', redact_auth_from_url(url))
  96. resp = session.get(
  97. url,
  98. headers={
  99. "Accept": "text/html",
  100. # We don't want to blindly returned cached data for
  101. # /simple/, because authors generally expecting that
  102. # twine upload && pip install will function, but if
  103. # they've done a pip install in the last ~10 minutes
  104. # it won't. Thus by setting this to zero we will not
  105. # blindly use any cached data, however the benefit of
  106. # using max-age=0 instead of no-cache, is that we will
  107. # still support conditional requests, so we will still
  108. # minimize traffic sent in cases where the page hasn't
  109. # changed at all, we will just always incur the round
  110. # trip for the conditional GET now instead of only
  111. # once per 10 minutes.
  112. # For more information, please see pypa/pip#5670.
  113. "Cache-Control": "max-age=0",
  114. },
  115. )
  116. resp.raise_for_status()
  117. # The check for archives above only works if the url ends with
  118. # something that looks like an archive. However that is not a
  119. # requirement of an url. Unless we issue a HEAD request on every
  120. # url we cannot know ahead of time for sure if something is HTML
  121. # or not. However we can check after we've downloaded it.
  122. _ensure_html_header(resp)
  123. return resp
  124. def _get_encoding_from_headers(headers):
  125. # type: (ResponseHeaders) -> Optional[str]
  126. """Determine if we have any encoding information in our headers.
  127. """
  128. if headers and "Content-Type" in headers:
  129. content_type, params = cgi.parse_header(headers["Content-Type"])
  130. if "charset" in params:
  131. return params['charset']
  132. return None
  133. def _determine_base_url(document, page_url):
  134. # type: (HTMLElement, 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. """
  144. for base in document.findall(".//base"):
  145. href = base.get("href")
  146. if href is not None:
  147. return href
  148. return page_url
  149. def _clean_link(url):
  150. # type: (str) -> str
  151. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  152. the link, it will be rewritten to %20 (while not over-quoting
  153. % or other characters)."""
  154. # Split the URL into parts according to the general structure
  155. # `scheme://netloc/path;parameters?query#fragment`. Note that the
  156. # `netloc` can be empty and the URI will then refer to a local
  157. # filesystem path.
  158. result = urllib_parse.urlparse(url)
  159. # In both cases below we unquote prior to quoting to make sure
  160. # nothing is double quoted.
  161. if result.netloc == "":
  162. # 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. path = urllib_request.pathname2url(
  167. urllib_request.url2pathname(result.path))
  168. else:
  169. # In addition to the `/` character we protect `@` so that
  170. # revision strings in VCS URLs are properly parsed.
  171. path = urllib_parse.quote(urllib_parse.unquote(result.path), safe="/@")
  172. return urllib_parse.urlunparse(result._replace(path=path))
  173. def _create_link_from_element(
  174. anchor, # type: HTMLElement
  175. page_url, # type: str
  176. base_url, # type: str
  177. ):
  178. # type: (...) -> Optional[Link]
  179. """
  180. Convert an anchor element in a simple repository page to a Link.
  181. """
  182. href = anchor.get("href")
  183. if not href:
  184. return None
  185. url = _clean_link(urllib_parse.urljoin(base_url, href))
  186. pyrequire = anchor.get('data-requires-python')
  187. pyrequire = unescape(pyrequire) if pyrequire else None
  188. yanked_reason = anchor.get('data-yanked')
  189. if yanked_reason:
  190. # This is a unicode string in Python 2 (and 3).
  191. yanked_reason = unescape(yanked_reason)
  192. link = Link(
  193. url,
  194. comes_from=page_url,
  195. requires_python=pyrequire,
  196. yanked_reason=yanked_reason,
  197. )
  198. return link
  199. def parse_links(page):
  200. # type: (HTMLPage) -> Iterable[Link]
  201. """
  202. Parse an HTML document, and yield its anchor elements as Link objects.
  203. """
  204. document = html5lib.parse(
  205. page.content,
  206. transport_encoding=page.encoding,
  207. namespaceHTMLElements=False,
  208. )
  209. url = page.url
  210. base_url = _determine_base_url(document, url)
  211. for anchor in document.findall(".//a"):
  212. link = _create_link_from_element(
  213. anchor,
  214. page_url=url,
  215. base_url=base_url,
  216. )
  217. if link is None:
  218. continue
  219. yield link
  220. class HTMLPage(object):
  221. """Represents one page, along with its URL"""
  222. def __init__(
  223. self,
  224. content, # type: bytes
  225. encoding, # type: Optional[str]
  226. url, # type: str
  227. ):
  228. # type: (...) -> None
  229. """
  230. :param encoding: the encoding to decode the given content.
  231. :param url: the URL from which the HTML was downloaded.
  232. """
  233. self.content = content
  234. self.encoding = encoding
  235. self.url = url
  236. def __str__(self):
  237. return redact_auth_from_url(self.url)
  238. def _handle_get_page_fail(
  239. link, # type: Link
  240. reason, # type: Union[str, Exception]
  241. meth=None # type: Optional[Callable[..., None]]
  242. ):
  243. # type: (...) -> None
  244. if meth is None:
  245. meth = logger.debug
  246. meth("Could not fetch URL %s: %s - skipping", link, reason)
  247. def _make_html_page(response):
  248. # type: (Response) -> HTMLPage
  249. encoding = _get_encoding_from_headers(response.headers)
  250. return HTMLPage(response.content, encoding=encoding, url=response.url)
  251. def _get_html_page(link, session=None):
  252. # type: (Link, Optional[PipSession]) -> Optional[HTMLPage]
  253. if session is None:
  254. raise TypeError(
  255. "_get_html_page() missing 1 required keyword argument: 'session'"
  256. )
  257. url = link.url.split('#', 1)[0]
  258. # Check for VCS schemes that do not support lookup as web pages.
  259. vcs_scheme = _match_vcs_scheme(url)
  260. if vcs_scheme:
  261. logger.debug('Cannot look at %s URL %s', vcs_scheme, link)
  262. return None
  263. # Tack index.html onto file:// URLs that point to directories
  264. scheme, _, path, _, _, _ = urllib_parse.urlparse(url)
  265. if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))):
  266. # add trailing slash if not present so urljoin doesn't trim
  267. # final segment
  268. if not url.endswith('/'):
  269. url += '/'
  270. url = urllib_parse.urljoin(url, 'index.html')
  271. logger.debug(' file: URL is directory, getting %s', url)
  272. try:
  273. resp = _get_html_response(url, session=session)
  274. except _NotHTTP:
  275. logger.debug(
  276. 'Skipping page %s because it looks like an archive, and cannot '
  277. 'be checked by HEAD.', link,
  278. )
  279. except _NotHTML as exc:
  280. logger.debug(
  281. 'Skipping page %s because the %s request got Content-Type: %s',
  282. link, exc.request_desc, exc.content_type,
  283. )
  284. except HTTPError as exc:
  285. _handle_get_page_fail(link, exc)
  286. except RetryError as exc:
  287. _handle_get_page_fail(link, exc)
  288. except SSLError as exc:
  289. reason = "There was a problem confirming the ssl certificate: "
  290. reason += str(exc)
  291. _handle_get_page_fail(link, reason, meth=logger.info)
  292. except requests.ConnectionError as exc:
  293. _handle_get_page_fail(link, "connection error: %s" % exc)
  294. except requests.Timeout:
  295. _handle_get_page_fail(link, "timed out")
  296. else:
  297. return _make_html_page(resp)
  298. return None
  299. def _remove_duplicate_links(links):
  300. # type: (Iterable[Link]) -> List[Link]
  301. """
  302. Return a list of links, with duplicates removed and ordering preserved.
  303. """
  304. # We preserve the ordering when removing duplicates because we can.
  305. return list(OrderedDict.fromkeys(links))
  306. def group_locations(locations, expand_dir=False):
  307. # type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
  308. """
  309. Divide a list of locations into two groups: "files" (archives) and "urls."
  310. :return: A pair of lists (files, urls).
  311. """
  312. files = []
  313. urls = []
  314. # puts the url for the given file path into the appropriate list
  315. def sort_path(path):
  316. url = path_to_url(path)
  317. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  318. urls.append(url)
  319. else:
  320. files.append(url)
  321. for url in locations:
  322. is_local_path = os.path.exists(url)
  323. is_file_url = url.startswith('file:')
  324. if is_local_path or is_file_url:
  325. if is_local_path:
  326. path = url
  327. else:
  328. path = url_to_path(url)
  329. if os.path.isdir(path):
  330. if expand_dir:
  331. path = os.path.realpath(path)
  332. for item in os.listdir(path):
  333. sort_path(os.path.join(path, item))
  334. elif is_file_url:
  335. urls.append(url)
  336. else:
  337. logger.warning(
  338. "Path '{0}' is ignored: "
  339. "it is a directory.".format(path),
  340. )
  341. elif os.path.isfile(path):
  342. sort_path(path)
  343. else:
  344. logger.warning(
  345. "Url '%s' is ignored: it is neither a file "
  346. "nor a directory.", url,
  347. )
  348. elif is_url(url):
  349. # Only add url with clear scheme
  350. urls.append(url)
  351. else:
  352. logger.warning(
  353. "Url '%s' is ignored. It is either a non-existing "
  354. "path or lacks a specific scheme.", url,
  355. )
  356. return files, urls
  357. class CollectedLinks(object):
  358. """
  359. Encapsulates all the Link objects collected by a call to
  360. LinkCollector.collect_links(), stored separately as--
  361. (1) links from the configured file locations,
  362. (2) links from the configured find_links, and
  363. (3) a dict mapping HTML page url to links from that page.
  364. """
  365. def __init__(
  366. self,
  367. files, # type: List[Link]
  368. find_links, # type: List[Link]
  369. pages, # type: Dict[str, List[Link]]
  370. ):
  371. # type: (...) -> None
  372. """
  373. :param files: Links from file locations.
  374. :param find_links: Links from find_links.
  375. :param pages: A dict mapping HTML page url to links from that page.
  376. """
  377. self.files = files
  378. self.find_links = find_links
  379. self.pages = pages
  380. class LinkCollector(object):
  381. """
  382. Responsible for collecting Link objects from all configured locations,
  383. making network requests as needed.
  384. The class's main method is its collect_links() method.
  385. """
  386. def __init__(
  387. self,
  388. session, # type: PipSession
  389. search_scope, # type: SearchScope
  390. ):
  391. # type: (...) -> None
  392. self.search_scope = search_scope
  393. self.session = session
  394. @property
  395. def find_links(self):
  396. # type: () -> List[str]
  397. return self.search_scope.find_links
  398. def _get_pages(self, locations):
  399. # type: (Iterable[Link]) -> Iterable[HTMLPage]
  400. """
  401. Yields (page, page_url) from the given locations, skipping
  402. locations that have errors.
  403. """
  404. for location in locations:
  405. page = _get_html_page(location, session=self.session)
  406. if page is None:
  407. continue
  408. yield page
  409. def collect_links(self, project_name):
  410. # type: (str) -> CollectedLinks
  411. """Find all available links for the given project name.
  412. :return: All the Link objects (unfiltered), as a CollectedLinks object.
  413. """
  414. search_scope = self.search_scope
  415. index_locations = search_scope.get_index_urls_locations(project_name)
  416. index_file_loc, index_url_loc = group_locations(index_locations)
  417. fl_file_loc, fl_url_loc = group_locations(
  418. self.find_links, expand_dir=True,
  419. )
  420. file_links = [
  421. Link(url) for url in itertools.chain(index_file_loc, fl_file_loc)
  422. ]
  423. # We trust every directly linked archive in find_links
  424. find_link_links = [Link(url, '-f') for url in self.find_links]
  425. # We trust every url that the user has given us whether it was given
  426. # via --index-url or --find-links.
  427. # We want to filter out anything that does not have a secure origin.
  428. url_locations = [
  429. link for link in itertools.chain(
  430. (Link(url) for url in index_url_loc),
  431. (Link(url) for url in fl_url_loc),
  432. )
  433. if self.session.is_secure_origin(link)
  434. ]
  435. url_locations = _remove_duplicate_links(url_locations)
  436. lines = [
  437. '{} location(s) to search for versions of {}:'.format(
  438. len(url_locations), project_name,
  439. ),
  440. ]
  441. for link in url_locations:
  442. lines.append('* {}'.format(link))
  443. logger.debug('\n'.join(lines))
  444. pages_links = {}
  445. for page in self._get_pages(url_locations):
  446. pages_links[page.url] = list(parse_links(page))
  447. return CollectedLinks(
  448. files=file_links,
  449. find_links=find_link_links,
  450. pages=pages_links,
  451. )