index.py 40 KB

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