index.py 40 KB

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