25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1109 lines
41 KiB

  1. """Routines related to PyPI, indexes"""
  2. from __future__ import absolute_import
  3. import cgi
  4. import itertools
  5. import logging
  6. import mimetypes
  7. import os
  8. import posixpath
  9. import re
  10. import sys
  11. from collections import namedtuple
  12. from pip._vendor import html5lib, requests, six
  13. from pip._vendor.distlib.compat import unescape
  14. from pip._vendor.packaging import specifiers
  15. from pip._vendor.packaging.utils import canonicalize_name
  16. from pip._vendor.packaging.version import parse as parse_version
  17. from pip._vendor.requests.exceptions import HTTPError, RetryError, SSLError
  18. from pip._vendor.six.moves.urllib import parse as urllib_parse
  19. from pip._vendor.six.moves.urllib import request as urllib_request
  20. from pip._internal.download import HAS_TLS, is_url, path_to_url, url_to_path
  21. from pip._internal.exceptions import (
  22. BestVersionAlreadyInstalled, DistributionNotFound, InvalidWheelFilename,
  23. UnsupportedWheel,
  24. )
  25. from pip._internal.models.candidate import InstallationCandidate
  26. from pip._internal.models.format_control import FormatControl
  27. from pip._internal.models.index import PyPI
  28. from pip._internal.models.link import Link
  29. from pip._internal.pep425tags import get_supported
  30. from pip._internal.utils.compat import ipaddress
  31. from pip._internal.utils.logging import indent_log
  32. from pip._internal.utils.misc import (
  33. ARCHIVE_EXTENSIONS, SUPPORTED_EXTENSIONS, WHEEL_EXTENSION, normalize_path,
  34. redact_password_from_url,
  35. )
  36. from pip._internal.utils.packaging import check_requires_python
  37. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  38. from pip._internal.wheel import Wheel
  39. if MYPY_CHECK_RUNNING:
  40. from logging import Logger
  41. from typing import (
  42. Tuple, Optional, Any, List, Union, Callable, Set, Sequence,
  43. Iterable, MutableMapping
  44. )
  45. from pip._vendor.packaging.version import _BaseVersion
  46. from pip._vendor.requests import Response
  47. from pip._internal.pep425tags import Pep425Tag
  48. from pip._internal.req import InstallRequirement
  49. from pip._internal.download import PipSession
  50. SecureOrigin = Tuple[str, str, Optional[str]]
  51. BuildTag = Tuple[Any, ...] # either empty tuple or Tuple[int, str]
  52. CandidateSortingKey = Tuple[int, _BaseVersion, BuildTag, Optional[int]]
  53. __all__ = ['FormatControl', 'FoundCandidates', 'PackageFinder']
  54. SECURE_ORIGINS = [
  55. # protocol, hostname, port
  56. # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
  57. ("https", "*", "*"),
  58. ("*", "localhost", "*"),
  59. ("*", "127.0.0.0/8", "*"),
  60. ("*", "::1/128", "*"),
  61. ("file", "*", None),
  62. # ssh is always secure.
  63. ("ssh", "*", "*"),
  64. ] # type: List[SecureOrigin]
  65. logger = logging.getLogger(__name__)
  66. def _match_vcs_scheme(url):
  67. # type: (str) -> Optional[str]
  68. """Look for VCS schemes in the URL.
  69. Returns the matched VCS scheme, or None if there's no match.
  70. """
  71. from pip._internal.vcs import VcsSupport
  72. for scheme in VcsSupport.schemes:
  73. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  74. return scheme
  75. return None
  76. def _is_url_like_archive(url):
  77. # type: (str) -> bool
  78. """Return whether the URL looks like an archive.
  79. """
  80. filename = Link(url).filename
  81. for bad_ext in ARCHIVE_EXTENSIONS:
  82. if filename.endswith(bad_ext):
  83. return True
  84. return False
  85. class _NotHTML(Exception):
  86. def __init__(self, content_type, request_desc):
  87. # type: (str, str) -> None
  88. super(_NotHTML, self).__init__(content_type, request_desc)
  89. self.content_type = content_type
  90. self.request_desc = request_desc
  91. def _ensure_html_header(response):
  92. # type: (Response) -> None
  93. """Check the Content-Type header to ensure the response contains HTML.
  94. Raises `_NotHTML` if the content type is not text/html.
  95. """
  96. content_type = response.headers.get("Content-Type", "")
  97. if not content_type.lower().startswith("text/html"):
  98. raise _NotHTML(content_type, response.request.method)
  99. class _NotHTTP(Exception):
  100. pass
  101. def _ensure_html_response(url, session):
  102. # type: (str, PipSession) -> None
  103. """Send a HEAD request to the URL, and ensure the response contains HTML.
  104. Raises `_NotHTTP` if the URL is not available for a HEAD request, or
  105. `_NotHTML` if the content type is not text/html.
  106. """
  107. scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
  108. if scheme not in {'http', 'https'}:
  109. raise _NotHTTP()
  110. resp = session.head(url, allow_redirects=True)
  111. resp.raise_for_status()
  112. _ensure_html_header(resp)
  113. def _get_html_response(url, session):
  114. # type: (str, PipSession) -> Response
  115. """Access an HTML page with GET, and return the response.
  116. This consists of three parts:
  117. 1. If the URL looks suspiciously like an archive, send a HEAD first to
  118. check the Content-Type is HTML, to avoid downloading a large file.
  119. Raise `_NotHTTP` if the content type cannot be determined, or
  120. `_NotHTML` if it is not HTML.
  121. 2. Actually perform the request. Raise HTTP exceptions on network failures.
  122. 3. Check the Content-Type header to make sure we got HTML, and raise
  123. `_NotHTML` otherwise.
  124. """
  125. if _is_url_like_archive(url):
  126. _ensure_html_response(url, session=session)
  127. logger.debug('Getting page %s', redact_password_from_url(url))
  128. resp = session.get(
  129. url,
  130. headers={
  131. "Accept": "text/html",
  132. # We don't want to blindly returned cached data for
  133. # /simple/, because authors generally expecting that
  134. # twine upload && pip install will function, but if
  135. # they've done a pip install in the last ~10 minutes
  136. # it won't. Thus by setting this to zero we will not
  137. # blindly use any cached data, however the benefit of
  138. # using max-age=0 instead of no-cache, is that we will
  139. # still support conditional requests, so we will still
  140. # minimize traffic sent in cases where the page hasn't
  141. # changed at all, we will just always incur the round
  142. # trip for the conditional GET now instead of only
  143. # once per 10 minutes.
  144. # For more information, please see pypa/pip#5670.
  145. "Cache-Control": "max-age=0",
  146. },
  147. )
  148. resp.raise_for_status()
  149. # The check for archives above only works if the url ends with
  150. # something that looks like an archive. However that is not a
  151. # requirement of an url. Unless we issue a HEAD request on every
  152. # url we cannot know ahead of time for sure if something is HTML
  153. # or not. However we can check after we've downloaded it.
  154. _ensure_html_header(resp)
  155. return resp
  156. def _handle_get_page_fail(
  157. link, # type: Link
  158. reason, # type: Union[str, Exception]
  159. meth=None # type: Optional[Callable[..., None]]
  160. ):
  161. # type: (...) -> None
  162. if meth is None:
  163. meth = logger.debug
  164. meth("Could not fetch URL %s: %s - skipping", link, reason)
  165. def _get_html_page(link, session=None):
  166. # type: (Link, Optional[PipSession]) -> Optional[HTMLPage]
  167. if session is None:
  168. raise TypeError(
  169. "_get_html_page() missing 1 required keyword argument: 'session'"
  170. )
  171. url = link.url.split('#', 1)[0]
  172. # Check for VCS schemes that do not support lookup as web pages.
  173. vcs_scheme = _match_vcs_scheme(url)
  174. if vcs_scheme:
  175. logger.debug('Cannot look at %s URL %s', vcs_scheme, link)
  176. return None
  177. # Tack index.html onto file:// URLs that point to directories
  178. scheme, _, path, _, _, _ = urllib_parse.urlparse(url)
  179. if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))):
  180. # add trailing slash if not present so urljoin doesn't trim
  181. # final segment
  182. if not url.endswith('/'):
  183. url += '/'
  184. url = urllib_parse.urljoin(url, 'index.html')
  185. logger.debug(' file: URL is directory, getting %s', url)
  186. try:
  187. resp = _get_html_response(url, session=session)
  188. except _NotHTTP:
  189. logger.debug(
  190. 'Skipping page %s because it looks like an archive, and cannot '
  191. 'be checked by HEAD.', link,
  192. )
  193. except _NotHTML as exc:
  194. logger.debug(
  195. 'Skipping page %s because the %s request got Content-Type: %s',
  196. link, exc.request_desc, exc.content_type,
  197. )
  198. except HTTPError as exc:
  199. _handle_get_page_fail(link, exc)
  200. except RetryError as exc:
  201. _handle_get_page_fail(link, exc)
  202. except SSLError as exc:
  203. reason = "There was a problem confirming the ssl certificate: "
  204. reason += str(exc)
  205. _handle_get_page_fail(link, reason, meth=logger.info)
  206. except requests.ConnectionError as exc:
  207. _handle_get_page_fail(link, "connection error: %s" % exc)
  208. except requests.Timeout:
  209. _handle_get_page_fail(link, "timed out")
  210. else:
  211. return HTMLPage(resp.content, resp.url, resp.headers)
  212. return None
  213. class CandidateEvaluator(object):
  214. def __init__(
  215. self,
  216. valid_tags, # type: List[Pep425Tag]
  217. prefer_binary=False # type: bool
  218. ):
  219. # type: (...) -> None
  220. self._prefer_binary = prefer_binary
  221. self._valid_tags = valid_tags
  222. def is_wheel_supported(self, wheel):
  223. # type: (Wheel) -> bool
  224. return wheel.supported(self._valid_tags)
  225. def _sort_key(self, candidate):
  226. # type: (InstallationCandidate) -> CandidateSortingKey
  227. """
  228. Function used to generate link sort key for link tuples.
  229. The greater the return value, the more preferred it is.
  230. If not finding wheels, then sorted by version only.
  231. If finding wheels, then the sort order is by version, then:
  232. 1. existing installs
  233. 2. wheels ordered via Wheel.support_index_min(self._valid_tags)
  234. 3. source archives
  235. If prefer_binary was set, then all wheels are sorted above sources.
  236. Note: it was considered to embed this logic into the Link
  237. comparison operators, but then different sdist links
  238. with the same version, would have to be considered equal
  239. """
  240. support_num = len(self._valid_tags)
  241. build_tag = tuple() # type: BuildTag
  242. binary_preference = 0
  243. if candidate.location.is_wheel:
  244. # can raise InvalidWheelFilename
  245. wheel = Wheel(candidate.location.filename)
  246. if not wheel.supported(self._valid_tags):
  247. raise UnsupportedWheel(
  248. "%s is not a supported wheel for this platform. It "
  249. "can't be sorted." % wheel.filename
  250. )
  251. if self._prefer_binary:
  252. binary_preference = 1
  253. pri = -(wheel.support_index_min(self._valid_tags))
  254. if wheel.build_tag is not None:
  255. match = re.match(r'^(\d+)(.*)$', wheel.build_tag)
  256. build_tag_groups = match.groups()
  257. build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
  258. else: # sdist
  259. pri = -(support_num)
  260. return (binary_preference, candidate.version, build_tag, pri)
  261. def get_best_candidate(self, candidates):
  262. # type: (List[InstallationCandidate]) -> InstallationCandidate
  263. """
  264. Return the best candidate per the instance's sort order, or None if
  265. no candidates are given.
  266. """
  267. if not candidates:
  268. return None
  269. return max(candidates, key=self._sort_key)
  270. class FoundCandidates(object):
  271. """A collection of candidates, returned by `PackageFinder.find_candidates`.
  272. This class is only intended to be instantiated by PackageFinder through
  273. the `from_specifier()` constructor.
  274. Arguments:
  275. * `candidates`: A sequence of all available candidates found.
  276. * `specifier`: Specifier to filter applicable versions.
  277. * `prereleases`: Whether prereleases should be accounted. Pass None to
  278. infer from the specifier.
  279. * `evaluator`: A CandidateEvaluator object to sort applicable candidates
  280. by order of preference.
  281. """
  282. def __init__(
  283. self,
  284. candidates, # type: List[InstallationCandidate]
  285. versions, # type: Set[str]
  286. evaluator, # type: CandidateEvaluator
  287. ):
  288. # type: (...) -> None
  289. self._candidates = candidates
  290. self._evaluator = evaluator
  291. self._versions = versions
  292. @classmethod
  293. def from_specifier(
  294. cls,
  295. candidates, # type: List[InstallationCandidate]
  296. specifier, # type: specifiers.BaseSpecifier
  297. prereleases, # type: Optional[bool]
  298. evaluator, # type: CandidateEvaluator
  299. ):
  300. # type: (...) -> FoundCandidates
  301. versions = {
  302. str(v) for v in specifier.filter(
  303. # We turn the version object into a str here because otherwise
  304. # when we're debundled but setuptools isn't, Python will see
  305. # packaging.version.Version and
  306. # pkg_resources._vendor.packaging.version.Version as different
  307. # types. This way we'll use a str as a common data interchange
  308. # format. If we stop using the pkg_resources provided specifier
  309. # and start using our own, we can drop the cast to str().
  310. (str(c.version) for c in candidates),
  311. prereleases=prereleases,
  312. )
  313. }
  314. return cls(candidates, versions, evaluator)
  315. def iter_all(self):
  316. # type: () -> Iterable[InstallationCandidate]
  317. """Iterate through all candidates.
  318. """
  319. return iter(self._candidates)
  320. def iter_applicable(self):
  321. # type: () -> Iterable[InstallationCandidate]
  322. """Iterate through candidates matching the versions associated with
  323. this instance.
  324. """
  325. # Again, converting version to str to deal with debundling.
  326. return (c for c in self.iter_all() if str(c.version) in self._versions)
  327. def get_best(self):
  328. # type: () -> Optional[InstallationCandidate]
  329. """Return the best candidate available, or None if no applicable
  330. candidates are found.
  331. """
  332. candidates = list(self.iter_applicable())
  333. return self._evaluator.get_best_candidate(candidates)
  334. class PackageFinder(object):
  335. """This finds packages.
  336. This is meant to match easy_install's technique for looking for
  337. packages, by reading pages and looking for appropriate links.
  338. """
  339. def __init__(
  340. self,
  341. find_links, # type: List[str]
  342. index_urls, # type: List[str]
  343. allow_all_prereleases=False, # type: bool
  344. trusted_hosts=None, # type: Optional[Iterable[str]]
  345. session=None, # type: Optional[PipSession]
  346. format_control=None, # type: Optional[FormatControl]
  347. platform=None, # type: Optional[str]
  348. versions=None, # type: Optional[List[str]]
  349. abi=None, # type: Optional[str]
  350. implementation=None, # type: Optional[str]
  351. prefer_binary=False # type: bool
  352. ):
  353. # type: (...) -> None
  354. """Create a PackageFinder.
  355. :param format_control: A FormatControl object or None. Used to control
  356. the selection of source packages / binary packages when consulting
  357. the index and links.
  358. :param platform: A string or None. If None, searches for packages
  359. that are supported by the current system. Otherwise, will find
  360. packages that can be built on the platform passed in. These
  361. packages will only be downloaded for distribution: they will
  362. not be built locally.
  363. :param versions: A list of strings or None. This is passed directly
  364. to pep425tags.py in the get_supported() method.
  365. :param abi: A string or None. This is passed directly
  366. to pep425tags.py in the get_supported() method.
  367. :param implementation: A string or None. This is passed directly
  368. to pep425tags.py in the get_supported() method.
  369. :param prefer_binary: Whether to prefer an old, but valid, binary
  370. dist over a new source dist.
  371. """
  372. if session is None:
  373. raise TypeError(
  374. "PackageFinder() missing 1 required keyword argument: "
  375. "'session'"
  376. )
  377. # Build find_links. If an argument starts with ~, it may be
  378. # a local file relative to a home directory. So try normalizing
  379. # it and if it exists, use the normalized version.
  380. # This is deliberately conservative - it might be fine just to
  381. # blindly normalize anything starting with a ~...
  382. self.find_links = [] # type: List[str]
  383. for link in find_links:
  384. if link.startswith('~'):
  385. new_link = normalize_path(link)
  386. if os.path.exists(new_link):
  387. link = new_link
  388. self.find_links.append(link)
  389. self.index_urls = index_urls
  390. # These are boring links that have already been logged somehow:
  391. self.logged_links = set() # type: Set[Link]
  392. self.format_control = format_control or FormatControl(set(), set())
  393. # Domains that we won't emit warnings for when not using HTTPS
  394. self.secure_origins = [
  395. ("*", host, "*")
  396. for host in (trusted_hosts if trusted_hosts else [])
  397. ] # type: List[SecureOrigin]
  398. # Do we want to allow _all_ pre-releases?
  399. self.allow_all_prereleases = allow_all_prereleases
  400. # The Session we'll use to make requests
  401. self.session = session
  402. # The valid tags to check potential found wheel candidates against
  403. valid_tags = get_supported(
  404. versions=versions,
  405. platform=platform,
  406. abi=abi,
  407. impl=implementation,
  408. )
  409. self.candidate_evaluator = CandidateEvaluator(
  410. valid_tags=valid_tags, prefer_binary=prefer_binary,
  411. )
  412. # If we don't have TLS enabled, then WARN if anyplace we're looking
  413. # relies on TLS.
  414. if not HAS_TLS:
  415. for link in itertools.chain(self.index_urls, self.find_links):
  416. parsed = urllib_parse.urlparse(link)
  417. if parsed.scheme == "https":
  418. logger.warning(
  419. "pip is configured with locations that require "
  420. "TLS/SSL, however the ssl module in Python is not "
  421. "available."
  422. )
  423. break
  424. def get_formatted_locations(self):
  425. # type: () -> str
  426. lines = []
  427. if self.index_urls and self.index_urls != [PyPI.simple_url]:
  428. lines.append(
  429. "Looking in indexes: {}".format(", ".join(
  430. redact_password_from_url(url) for url in self.index_urls))
  431. )
  432. if self.find_links:
  433. lines.append(
  434. "Looking in links: {}".format(", ".join(self.find_links))
  435. )
  436. return "\n".join(lines)
  437. @staticmethod
  438. def _sort_locations(locations, expand_dir=False):
  439. # type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
  440. """
  441. Sort locations into "files" (archives) and "urls", and return
  442. a pair of lists (files,urls)
  443. """
  444. files = []
  445. urls = []
  446. # puts the url for the given file path into the appropriate list
  447. def sort_path(path):
  448. url = path_to_url(path)
  449. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  450. urls.append(url)
  451. else:
  452. files.append(url)
  453. for url in locations:
  454. is_local_path = os.path.exists(url)
  455. is_file_url = url.startswith('file:')
  456. if is_local_path or is_file_url:
  457. if is_local_path:
  458. path = url
  459. else:
  460. path = url_to_path(url)
  461. if os.path.isdir(path):
  462. if expand_dir:
  463. path = os.path.realpath(path)
  464. for item in os.listdir(path):
  465. sort_path(os.path.join(path, item))
  466. elif is_file_url:
  467. urls.append(url)
  468. else:
  469. logger.warning(
  470. "Path '{0}' is ignored: "
  471. "it is a directory.".format(path),
  472. )
  473. elif os.path.isfile(path):
  474. sort_path(path)
  475. else:
  476. logger.warning(
  477. "Url '%s' is ignored: it is neither a file "
  478. "nor a directory.", url,
  479. )
  480. elif is_url(url):
  481. # Only add url with clear scheme
  482. urls.append(url)
  483. else:
  484. logger.warning(
  485. "Url '%s' is ignored. It is either a non-existing "
  486. "path or lacks a specific scheme.", url,
  487. )
  488. return files, urls
  489. def _validate_secure_origin(self, logger, location):
  490. # type: (Logger, Link) -> bool
  491. # Determine if this url used a secure transport mechanism
  492. parsed = urllib_parse.urlparse(str(location))
  493. origin = (parsed.scheme, parsed.hostname, parsed.port)
  494. # The protocol to use to see if the protocol matches.
  495. # Don't count the repository type as part of the protocol: in
  496. # cases such as "git+ssh", only use "ssh". (I.e., Only verify against
  497. # the last scheme.)
  498. protocol = origin[0].rsplit('+', 1)[-1]
  499. # Determine if our origin is a secure origin by looking through our
  500. # hardcoded list of secure origins, as well as any additional ones
  501. # configured on this PackageFinder instance.
  502. for secure_origin in (SECURE_ORIGINS + self.secure_origins):
  503. if protocol != secure_origin[0] and secure_origin[0] != "*":
  504. continue
  505. try:
  506. # We need to do this decode dance to ensure that we have a
  507. # unicode object, even on Python 2.x.
  508. addr = ipaddress.ip_address(
  509. origin[1]
  510. if (
  511. isinstance(origin[1], six.text_type) or
  512. origin[1] is None
  513. )
  514. else origin[1].decode("utf8")
  515. )
  516. network = ipaddress.ip_network(
  517. secure_origin[1]
  518. if isinstance(secure_origin[1], six.text_type)
  519. # setting secure_origin[1] to proper Union[bytes, str]
  520. # creates problems in other places
  521. else secure_origin[1].decode("utf8") # type: ignore
  522. )
  523. except ValueError:
  524. # We don't have both a valid address or a valid network, so
  525. # we'll check this origin against hostnames.
  526. if (origin[1] and
  527. origin[1].lower() != secure_origin[1].lower() and
  528. secure_origin[1] != "*"):
  529. continue
  530. else:
  531. # We have a valid address and network, so see if the address
  532. # is contained within the network.
  533. if addr not in network:
  534. continue
  535. # Check to see if the port patches
  536. if (origin[2] != secure_origin[2] and
  537. secure_origin[2] != "*" and
  538. secure_origin[2] is not None):
  539. continue
  540. # If we've gotten here, then this origin matches the current
  541. # secure origin and we should return True
  542. return True
  543. # If we've gotten to this point, then the origin isn't secure and we
  544. # will not accept it as a valid location to search. We will however
  545. # log a warning that we are ignoring it.
  546. logger.warning(
  547. "The repository located at %s is not a trusted or secure host and "
  548. "is being ignored. If this repository is available via HTTPS we "
  549. "recommend you use HTTPS instead, otherwise you may silence "
  550. "this warning and allow it anyway with '--trusted-host %s'.",
  551. parsed.hostname,
  552. parsed.hostname,
  553. )
  554. return False
  555. def _get_index_urls_locations(self, project_name):
  556. # type: (str) -> List[str]
  557. """Returns the locations found via self.index_urls
  558. Checks the url_name on the main (first in the list) index and
  559. use this url_name to produce all locations
  560. """
  561. def mkurl_pypi_url(url):
  562. loc = posixpath.join(
  563. url,
  564. urllib_parse.quote(canonicalize_name(project_name)))
  565. # For maximum compatibility with easy_install, ensure the path
  566. # ends in a trailing slash. Although this isn't in the spec
  567. # (and PyPI can handle it without the slash) some other index
  568. # implementations might break if they relied on easy_install's
  569. # behavior.
  570. if not loc.endswith('/'):
  571. loc = loc + '/'
  572. return loc
  573. return [mkurl_pypi_url(url) for url in self.index_urls]
  574. def find_all_candidates(self, project_name):
  575. # type: (str) -> List[Optional[InstallationCandidate]]
  576. """Find all available InstallationCandidate for project_name
  577. This checks index_urls and find_links.
  578. All versions found are returned as an InstallationCandidate list.
  579. See _link_package_versions for details on which files are accepted
  580. """
  581. index_locations = self._get_index_urls_locations(project_name)
  582. index_file_loc, index_url_loc = self._sort_locations(index_locations)
  583. fl_file_loc, fl_url_loc = self._sort_locations(
  584. self.find_links, expand_dir=True,
  585. )
  586. file_locations = (Link(url) for url in itertools.chain(
  587. index_file_loc, fl_file_loc,
  588. ))
  589. # We trust every url that the user has given us whether it was given
  590. # via --index-url or --find-links.
  591. # We want to filter out any thing which does not have a secure origin.
  592. url_locations = [
  593. link for link in itertools.chain(
  594. (Link(url) for url in index_url_loc),
  595. (Link(url) for url in fl_url_loc),
  596. )
  597. if self._validate_secure_origin(logger, link)
  598. ]
  599. logger.debug('%d location(s) to search for versions of %s:',
  600. len(url_locations), project_name)
  601. for location in url_locations:
  602. logger.debug('* %s', location)
  603. canonical_name = canonicalize_name(project_name)
  604. formats = self.format_control.get_allowed_formats(canonical_name)
  605. search = Search(project_name, canonical_name, formats)
  606. find_links_versions = self._package_versions(
  607. # We trust every directly linked archive in find_links
  608. (Link(url, '-f') for url in self.find_links),
  609. search
  610. )
  611. page_versions = []
  612. for page in self._get_pages(url_locations, project_name):
  613. logger.debug('Analyzing links from page %s', page.url)
  614. with indent_log():
  615. page_versions.extend(
  616. self._package_versions(page.iter_links(), search)
  617. )
  618. file_versions = self._package_versions(file_locations, search)
  619. if file_versions:
  620. file_versions.sort(reverse=True)
  621. logger.debug(
  622. 'Local files found: %s',
  623. ', '.join([
  624. url_to_path(candidate.location.url)
  625. for candidate in file_versions
  626. ])
  627. )
  628. # This is an intentional priority ordering
  629. return file_versions + find_links_versions + page_versions
  630. def find_candidates(
  631. self,
  632. project_name, # type: str
  633. specifier=None, # type: Optional[specifiers.BaseSpecifier]
  634. ):
  635. """Find matches for the given project and specifier.
  636. If given, `specifier` should implement `filter` to allow version
  637. filtering (e.g. ``packaging.specifiers.SpecifierSet``).
  638. Returns a `FoundCandidates` instance.
  639. """
  640. if specifier is None:
  641. specifier = specifiers.SpecifierSet()
  642. return FoundCandidates.from_specifier(
  643. self.find_all_candidates(project_name),
  644. specifier=specifier,
  645. prereleases=(self.allow_all_prereleases or None),
  646. evaluator=self.candidate_evaluator,
  647. )
  648. def find_requirement(self, req, upgrade):
  649. # type: (InstallRequirement, bool) -> Optional[Link]
  650. """Try to find a Link matching req
  651. Expects req, an InstallRequirement and upgrade, a boolean
  652. Returns a Link if found,
  653. Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
  654. """
  655. candidates = self.find_candidates(req.name, req.specifier)
  656. best_candidate = candidates.get_best()
  657. installed_version = None # type: Optional[_BaseVersion]
  658. if req.satisfied_by is not None:
  659. installed_version = parse_version(req.satisfied_by.version)
  660. def _format_versions(cand_iter):
  661. # This repeated parse_version and str() conversion is needed to
  662. # handle different vendoring sources from pip and pkg_resources.
  663. # If we stop using the pkg_resources provided specifier and start
  664. # using our own, we can drop the cast to str().
  665. return ", ".join(sorted(
  666. {str(c.version) for c in cand_iter},
  667. key=parse_version,
  668. )) or "none"
  669. if installed_version is None and best_candidate is None:
  670. logger.critical(
  671. 'Could not find a version that satisfies the requirement %s '
  672. '(from versions: %s)',
  673. req,
  674. _format_versions(candidates.iter_all()),
  675. )
  676. raise DistributionNotFound(
  677. 'No matching distribution found for %s' % req
  678. )
  679. best_installed = False
  680. if installed_version and (
  681. best_candidate is None or
  682. best_candidate.version <= installed_version):
  683. best_installed = True
  684. if not upgrade and installed_version is not None:
  685. if best_installed:
  686. logger.debug(
  687. 'Existing installed version (%s) is most up-to-date and '
  688. 'satisfies requirement',
  689. installed_version,
  690. )
  691. else:
  692. logger.debug(
  693. 'Existing installed version (%s) satisfies requirement '
  694. '(most up-to-date version is %s)',
  695. installed_version,
  696. best_candidate.version,
  697. )
  698. return None
  699. if best_installed:
  700. # We have an existing version, and its the best version
  701. logger.debug(
  702. 'Installed version (%s) is most up-to-date (past versions: '
  703. '%s)',
  704. installed_version,
  705. _format_versions(candidates.iter_applicable()),
  706. )
  707. raise BestVersionAlreadyInstalled
  708. logger.debug(
  709. 'Using version %s (newest of versions: %s)',
  710. best_candidate.version,
  711. _format_versions(candidates.iter_applicable()),
  712. )
  713. return best_candidate.location
  714. def _get_pages(self, locations, project_name):
  715. # type: (Iterable[Link], str) -> Iterable[HTMLPage]
  716. """
  717. Yields (page, page_url) from the given locations, skipping
  718. locations that have errors.
  719. """
  720. seen = set() # type: Set[Link]
  721. for location in locations:
  722. if location in seen:
  723. continue
  724. seen.add(location)
  725. page = _get_html_page(location, session=self.session)
  726. if page is None:
  727. continue
  728. yield page
  729. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  730. def _sort_links(self, links):
  731. # type: (Iterable[Link]) -> List[Link]
  732. """
  733. Returns elements of links in order, non-egg links first, egg links
  734. second, while eliminating duplicates
  735. """
  736. eggs, no_eggs = [], []
  737. seen = set() # type: Set[Link]
  738. for link in links:
  739. if link not in seen:
  740. seen.add(link)
  741. if link.egg_fragment:
  742. eggs.append(link)
  743. else:
  744. no_eggs.append(link)
  745. return no_eggs + eggs
  746. def _package_versions(
  747. self,
  748. links, # type: Iterable[Link]
  749. search # type: Search
  750. ):
  751. # type: (...) -> List[Optional[InstallationCandidate]]
  752. result = []
  753. for link in self._sort_links(links):
  754. v = self._link_package_versions(link, search)
  755. if v is not None:
  756. result.append(v)
  757. return result
  758. def _log_skipped_link(self, link, reason):
  759. # type: (Link, str) -> None
  760. if link not in self.logged_links:
  761. logger.debug('Skipping link %s; %s', link, reason)
  762. self.logged_links.add(link)
  763. def _link_package_versions(self, link, search):
  764. # type: (Link, Search) -> Optional[InstallationCandidate]
  765. """Return an InstallationCandidate or None"""
  766. version = None
  767. if link.egg_fragment:
  768. egg_info = link.egg_fragment
  769. ext = link.ext
  770. else:
  771. egg_info, ext = link.splitext()
  772. if not ext:
  773. self._log_skipped_link(link, 'not a file')
  774. return None
  775. if ext not in SUPPORTED_EXTENSIONS:
  776. self._log_skipped_link(
  777. link, 'unsupported archive format: %s' % ext,
  778. )
  779. return None
  780. if "binary" not in search.formats and ext == WHEEL_EXTENSION:
  781. self._log_skipped_link(
  782. link, 'No binaries permitted for %s' % search.supplied,
  783. )
  784. return None
  785. if "macosx10" in link.path and ext == '.zip':
  786. self._log_skipped_link(link, 'macosx10 one')
  787. return None
  788. if ext == WHEEL_EXTENSION:
  789. try:
  790. wheel = Wheel(link.filename)
  791. except InvalidWheelFilename:
  792. self._log_skipped_link(link, 'invalid wheel filename')
  793. return None
  794. if canonicalize_name(wheel.name) != search.canonical:
  795. self._log_skipped_link(
  796. link, 'wrong project name (not %s)' % search.supplied)
  797. return None
  798. if not self.candidate_evaluator.is_wheel_supported(wheel):
  799. self._log_skipped_link(
  800. link, 'it is not compatible with this Python')
  801. return None
  802. version = wheel.version
  803. # This should be up by the search.ok_binary check, but see issue 2700.
  804. if "source" not in search.formats and ext != WHEEL_EXTENSION:
  805. self._log_skipped_link(
  806. link, 'No sources permitted for %s' % search.supplied,
  807. )
  808. return None
  809. if not version:
  810. version = _egg_info_matches(egg_info, search.canonical)
  811. if not version:
  812. self._log_skipped_link(
  813. link, 'Missing project version for %s' % search.supplied)
  814. return None
  815. match = self._py_version_re.search(version)
  816. if match:
  817. version = version[:match.start()]
  818. py_version = match.group(1)
  819. if py_version != sys.version[:3]:
  820. self._log_skipped_link(
  821. link, 'Python version is incorrect')
  822. return None
  823. try:
  824. support_this_python = check_requires_python(link.requires_python)
  825. except specifiers.InvalidSpecifier:
  826. logger.debug("Package %s has an invalid Requires-Python entry: %s",
  827. link.filename, link.requires_python)
  828. support_this_python = True
  829. if not support_this_python:
  830. logger.debug("The package %s is incompatible with the python "
  831. "version in use. Acceptable python versions are: %s",
  832. link, link.requires_python)
  833. return None
  834. logger.debug('Found link %s, version: %s', link, version)
  835. return InstallationCandidate(search.supplied, version, link)
  836. def _find_name_version_sep(egg_info, canonical_name):
  837. # type: (str, str) -> int
  838. """Find the separator's index based on the package's canonical name.
  839. `egg_info` must be an egg info string for the given package, and
  840. `canonical_name` must be the package's canonical name.
  841. This function is needed since the canonicalized name does not necessarily
  842. have the same length as the egg info's name part. An example::
  843. >>> egg_info = 'foo__bar-1.0'
  844. >>> canonical_name = 'foo-bar'
  845. >>> _find_name_version_sep(egg_info, canonical_name)
  846. 8
  847. """
  848. # Project name and version must be separated by one single dash. Find all
  849. # occurrences of dashes; if the string in front of it matches the canonical
  850. # name, this is the one separating the name and version parts.
  851. for i, c in enumerate(egg_info):
  852. if c != "-":
  853. continue
  854. if canonicalize_name(egg_info[:i]) == canonical_name:
  855. return i
  856. raise ValueError("{} does not match {}".format(egg_info, canonical_name))
  857. def _egg_info_matches(egg_info, canonical_name):
  858. # type: (str, str) -> Optional[str]
  859. """Pull the version part out of a string.
  860. :param egg_info: The string to parse. E.g. foo-2.1
  861. :param canonical_name: The canonicalized name of the package this
  862. belongs to.
  863. """
  864. try:
  865. version_start = _find_name_version_sep(egg_info, canonical_name) + 1
  866. except ValueError:
  867. return None
  868. version = egg_info[version_start:]
  869. if not version:
  870. return None
  871. return version
  872. def _determine_base_url(document, page_url):
  873. """Determine the HTML document's base URL.
  874. This looks for a ``<base>`` tag in the HTML document. If present, its href
  875. attribute denotes the base URL of anchor tags in the document. If there is
  876. no such tag (or if it does not have a valid href attribute), the HTML
  877. file's URL is used as the base URL.
  878. :param document: An HTML document representation. The current
  879. implementation expects the result of ``html5lib.parse()``.
  880. :param page_url: The URL of the HTML document.
  881. """
  882. for base in document.findall(".//base"):
  883. href = base.get("href")
  884. if href is not None:
  885. return href
  886. return page_url
  887. def _get_encoding_from_headers(headers):
  888. """Determine if we have any encoding information in our headers.
  889. """
  890. if headers and "Content-Type" in headers:
  891. content_type, params = cgi.parse_header(headers["Content-Type"])
  892. if "charset" in params:
  893. return params['charset']
  894. return None
  895. def _clean_link(url):
  896. # type: (str) -> str
  897. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  898. the link, it will be rewritten to %20 (while not over-quoting
  899. % or other characters)."""
  900. # Split the URL into parts according to the general structure
  901. # `scheme://netloc/path;parameters?query#fragment`. Note that the
  902. # `netloc` can be empty and the URI will then refer to a local
  903. # filesystem path.
  904. result = urllib_parse.urlparse(url)
  905. # In both cases below we unquote prior to quoting to make sure
  906. # nothing is double quoted.
  907. if result.netloc == "":
  908. # On Windows the path part might contain a drive letter which
  909. # should not be quoted. On Linux where drive letters do not
  910. # exist, the colon should be quoted. We rely on urllib.request
  911. # to do the right thing here.
  912. path = urllib_request.pathname2url(
  913. urllib_request.url2pathname(result.path))
  914. else:
  915. # In addition to the `/` character we protect `@` so that
  916. # revision strings in VCS URLs are properly parsed.
  917. path = urllib_parse.quote(urllib_parse.unquote(result.path), safe="/@")
  918. return urllib_parse.urlunparse(result._replace(path=path))
  919. class HTMLPage(object):
  920. """Represents one page, along with its URL"""
  921. def __init__(self, content, url, headers=None):
  922. # type: (bytes, str, MutableMapping[str, str]) -> None
  923. self.content = content
  924. self.url = url
  925. self.headers = headers
  926. def __str__(self):
  927. return redact_password_from_url(self.url)
  928. def iter_links(self):
  929. # type: () -> Iterable[Link]
  930. """Yields all links in the page"""
  931. document = html5lib.parse(
  932. self.content,
  933. transport_encoding=_get_encoding_from_headers(self.headers),
  934. namespaceHTMLElements=False,
  935. )
  936. base_url = _determine_base_url(document, self.url)
  937. for anchor in document.findall(".//a"):
  938. if anchor.get("href"):
  939. href = anchor.get("href")
  940. url = _clean_link(urllib_parse.urljoin(base_url, href))
  941. pyrequire = anchor.get('data-requires-python')
  942. pyrequire = unescape(pyrequire) if pyrequire else None
  943. yield Link(url, self.url, requires_python=pyrequire)
  944. Search = namedtuple('Search', 'supplied canonical formats')
  945. """Capture key aspects of a search.
  946. :attribute supplied: The user supplied package.
  947. :attribute canonical: The canonical package name.
  948. :attribute formats: The formats allowed for this package. Should be a set
  949. with 'binary' or 'source' or both in it.
  950. """