Advertisement
AlanReiAkemi

asd

Dec 29th, 2015
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 47.99 KB | None | 0 0
  1. """Routines related to PyPI, indexes"""
  2. from __future__ import absolute_import
  3.  
  4. import logging
  5. import cgi
  6. from collections import namedtuple
  7. import itertools
  8. import sys
  9. import os
  10. import re
  11. import mimetypes
  12. import posixpath
  13. import warnings
  14.  
  15. from pip._vendor.six.moves.urllib import parse as urllib_parse
  16. from pip._vendor.six.moves.urllib import request as urllib_request
  17.  
  18. from pip.compat import ipaddress
  19. from pip.utils import (
  20. Inf, cached_property, normalize_name, splitext, normalize_path,
  21. ARCHIVE_EXTENSIONS, SUPPORTED_EXTENSIONS)
  22. from pip.utils.deprecation import RemovedInPip8Warning
  23. from pip.utils.logging import indent_log
  24. from pip.exceptions import (
  25. DistributionNotFound, BestVersionAlreadyInstalled, InvalidWheelFilename,
  26. UnsupportedWheel,
  27. )
  28. from pip.download import HAS_TLS, url_to_path, path_to_url
  29. from pip.models import PyPI
  30. from pip.wheel import Wheel, wheel_ext
  31. from pip.pep425tags import supported_tags, supported_tags_noarch, get_platform
  32. from pip._vendor import html5lib, requests, pkg_resources, six
  33. from pip._vendor.packaging.version import parse as parse_version
  34. from pip._vendor.requests.exceptions import SSLError
  35.  
  36.  
  37. __all__ = ['FormatControl', 'fmt_ctl_handle_mutual_exclude', 'PackageFinder']
  38.  
  39.  
  40. # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)
  41. SECURE_ORIGINS = [
  42. # protocol, hostname, port
  43. ("https", "*", "*"),
  44. ("*", "localhost", "*"),
  45. ("*", "127.0.0.0/8", "*"),
  46. ("*", "::1/128", "*"),
  47. ("file", "*", None),
  48. ]
  49.  
  50.  
  51. logger = logging.getLogger(__name__)
  52.  
  53.  
  54. class InstallationCandidate(object):
  55.  
  56. def __init__(self, project, version, location):
  57. self.project = project
  58. self.version = parse_version(version)
  59. self.location = location
  60. self._key = (self.project, self.version, self.location)
  61.  
  62. def __repr__(self):
  63. return "<InstallationCandidate({0!r}, {1!r}, {2!r})>".format(
  64. self.project, self.version, self.location,
  65. )
  66.  
  67. def __hash__(self):
  68. return hash(self._key)
  69.  
  70. def __lt__(self, other):
  71. return self._compare(other, lambda s, o: s < o)
  72.  
  73. def __le__(self, other):
  74. return self._compare(other, lambda s, o: s <= o)
  75.  
  76. def __eq__(self, other):
  77. return self._compare(other, lambda s, o: s == o)
  78.  
  79. def __ge__(self, other):
  80. return self._compare(other, lambda s, o: s >= o)
  81.  
  82. def __gt__(self, other):
  83. return self._compare(other, lambda s, o: s > o)
  84.  
  85. def __ne__(self, other):
  86. return self._compare(other, lambda s, o: s != o)
  87.  
  88. def _compare(self, other, method):
  89. if not isinstance(other, InstallationCandidate):
  90. return NotImplemented
  91.  
  92. return method(self._key, other._key)
  93.  
  94.  
  95. class PackageFinder(object):
  96. """This finds packages.
  97.  
  98. This is meant to match easy_install's technique for looking for
  99. packages, by reading pages and looking for appropriate links.
  100. """
  101.  
  102. def __init__(self, find_links, index_urls,
  103. allow_external=(), allow_unverified=(),
  104. allow_all_external=False, allow_all_prereleases=False,
  105. trusted_hosts=None, process_dependency_links=False,
  106. session=None, format_control=None):
  107. """Create a PackageFinder.
  108.  
  109. :param format_control: A FormatControl object or None. Used to control
  110. the selection of source packages / binary packages when consulting
  111. the index and links.
  112. """
  113. if session is None:
  114. raise TypeError(
  115. "PackageFinder() missing 1 required keyword argument: "
  116. "'session'"
  117. )
  118.  
  119. # Build find_links. If an argument starts with ~, it may be
  120. # a local file relative to a home directory. So try normalizing
  121. # it and if it exists, use the normalized version.
  122. # This is deliberately conservative - it might be fine just to
  123. # blindly normalize anything starting with a ~...
  124. self.find_links = []
  125. for link in find_links:
  126. if link.startswith('~'):
  127. new_link = normalize_path(link)
  128. if os.path.exists(new_link):
  129. link = new_link
  130. self.find_links.append(link)
  131.  
  132. self.index_urls = index_urls
  133. self.dependency_links = []
  134.  
  135. # These are boring links that have already been logged somehow:
  136. self.logged_links = set()
  137.  
  138. self.format_control = format_control or FormatControl(set(), set())
  139.  
  140. # Do we allow (safe and verifiable) externally hosted files?
  141. self.allow_external = set(normalize_name(n) for n in allow_external)
  142.  
  143. # Which names are allowed to install insecure and unverifiable files?
  144. self.allow_unverified = set(
  145. normalize_name(n) for n in allow_unverified
  146. )
  147.  
  148. # Anything that is allowed unverified is also allowed external
  149. self.allow_external |= self.allow_unverified
  150.  
  151. # Do we allow all (safe and verifiable) externally hosted files?
  152. self.allow_all_external = allow_all_external
  153.  
  154. # Domains that we won't emit warnings for when not using HTTPS
  155. self.secure_origins = [
  156. ("*", host, "*")
  157. for host in (trusted_hosts if trusted_hosts else [])
  158. ]
  159.  
  160. # Stores if we ignored any external links so that we can instruct
  161. # end users how to install them if no distributions are available
  162. self.need_warn_external = False
  163.  
  164. # Stores if we ignored any unsafe links so that we can instruct
  165. # end users how to install them if no distributions are available
  166. self.need_warn_unverified = False
  167.  
  168. # Do we want to allow _all_ pre-releases?
  169. self.allow_all_prereleases = allow_all_prereleases
  170.  
  171. # Do we process dependency links?
  172. self.process_dependency_links = process_dependency_links
  173.  
  174. # The Session we'll use to make requests
  175. self.session = session
  176.  
  177. # If we don't have TLS enabled, then WARN if anyplace we're looking
  178. # relies on TLS.
  179. if not HAS_TLS:
  180. for link in itertools.chain(self.index_urls, self.find_links):
  181. parsed = urllib_parse.urlparse(link)
  182. if parsed.scheme == "https":
  183. logger.warning(
  184. "pip is configured with locations that require "
  185. "TLS/SSL, however the ssl module in Python is not "
  186. "available."
  187. )
  188. break
  189.  
  190. def add_dependency_links(self, links):
  191. # # FIXME: this shouldn't be global list this, it should only
  192. # # apply to requirements of the package that specifies the
  193. # # dependency_links value
  194. # # FIXME: also, we should track comes_from (i.e., use Link)
  195. if self.process_dependency_links:
  196. warnings.warn(
  197. "Dependency Links processing has been deprecated and will be "
  198. "removed in a future release.",
  199. RemovedInPip8Warning,
  200. )
  201. self.dependency_links.extend(links)
  202.  
  203. @staticmethod
  204. def _sort_locations(locations, expand_dir=False):
  205. """
  206. Sort locations into "files" (archives) and "urls", and return
  207. a pair of lists (files,urls)
  208. """
  209. files = []
  210. urls = []
  211.  
  212. # puts the url for the given file path into the appropriate list
  213. def sort_path(path):
  214. url = path_to_url(path)
  215. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  216. urls.append(url)
  217. else:
  218. files.append(url)
  219.  
  220. for url in locations:
  221.  
  222. is_local_path = os.path.exists(url)
  223. is_file_url = url.startswith('file:')
  224.  
  225. if is_local_path or is_file_url:
  226. if is_local_path:
  227. path = url
  228. else:
  229. path = url_to_path(url)
  230. if os.path.isdir(path):
  231. if expand_dir:
  232. path = os.path.realpath(path)
  233. for item in os.listdir(path):
  234. sort_path(os.path.join(path, item))
  235. elif is_file_url:
  236. urls.append(url)
  237. elif os.path.isfile(path):
  238. sort_path(path)
  239. else:
  240. urls.append(url)
  241.  
  242. return files, urls
  243.  
  244. def _candidate_sort_key(self, candidate):
  245. """
  246. Function used to generate link sort key for link tuples.
  247. The greater the return value, the more preferred it is.
  248. If not finding wheels, then sorted by version only.
  249. If finding wheels, then the sort order is by version, then:
  250. 1. existing installs
  251. 2. wheels ordered via Wheel.support_index_min()
  252. 3. source archives
  253. Note: it was considered to embed this logic into the Link
  254. comparison operators, but then different sdist links
  255. with the same version, would have to be considered equal
  256. """
  257. support_num = len(supported_tags)
  258. if candidate.location == INSTALLED_VERSION:
  259. pri = 1
  260. elif candidate.location.is_wheel:
  261. # can raise InvalidWheelFilename
  262. wheel = Wheel(candidate.location.filename)
  263. if not wheel.supported():
  264. raise UnsupportedWheel(
  265. "%s is not a supported wheel for this platform. It "
  266. "can't be sorted." % wheel.filename
  267. )
  268. pri = -(wheel.support_index_min())
  269. else: # sdist
  270. pri = -(support_num)
  271. return (candidate.version, pri)
  272.  
  273. def _sort_versions(self, applicable_versions):
  274. """
  275. Bring the latest version (and wheels) to the front, but maintain the
  276. existing ordering as secondary. See the docstring for `_link_sort_key`
  277. for details. This function is isolated for easier unit testing.
  278. """
  279. return sorted(
  280. applicable_versions,
  281. key=self._candidate_sort_key,
  282. reverse=True
  283. )
  284.  
  285. def _validate_secure_origin(self, logger, location):
  286. # Determine if this url used a secure transport mechanism
  287. parsed = urllib_parse.urlparse(str(location))
  288. origin = (parsed.scheme, parsed.hostname, parsed.port)
  289.  
  290. # Determine if our origin is a secure origin by looking through our
  291. # hardcoded list of secure origins, as well as any additional ones
  292. # configured on this PackageFinder instance.
  293. for secure_origin in (SECURE_ORIGINS + self.secure_origins):
  294. # Check to see if the protocol matches
  295. if origin[0] != secure_origin[0] and secure_origin[0] != "*":
  296. continue
  297.  
  298. try:
  299. # We need to do this decode dance to ensure that we have a
  300. # unicode object, even on Python 2.x.
  301. addr = ipaddress.ip_address(
  302. origin[1]
  303. if (
  304. isinstance(origin[1], six.text_type) or
  305. origin[1] is None
  306. )
  307. else origin[1].decode("utf8")
  308. )
  309. network = ipaddress.ip_network(
  310. secure_origin[1]
  311. if isinstance(secure_origin[1], six.text_type)
  312. else secure_origin[1].decode("utf8")
  313. )
  314. except ValueError:
  315. # We don't have both a valid address or a valid network, so
  316. # we'll check this origin against hostnames.
  317. if origin[1] != secure_origin[1] and secure_origin[1] != "*":
  318. continue
  319. else:
  320. # We have a valid address and network, so see if the address
  321. # is contained within the network.
  322. if addr not in network:
  323. continue
  324.  
  325. # Check to see if the port patches
  326. if (origin[2] != secure_origin[2] and
  327. secure_origin[2] != "*" and
  328. secure_origin[2] is not None):
  329. continue
  330.  
  331. # If we've gotten here, then this origin matches the current
  332. # secure origin and we should return True
  333. return True
  334.  
  335. # If we've gotten to this point, then the origin isn't secure and we
  336. # will not accept it as a valid location to search. We will however
  337. # log a warning that we are ignoring it.
  338. logger.warning(
  339. "The repository located at %s is not a trusted or secure host and "
  340. "is being ignored. If this repository is available via HTTPS it "
  341. "is recommended to use HTTPS instead, otherwise you may silence "
  342. "this warning and allow it anyways with '--trusted-host %s'.",
  343. parsed.hostname,
  344. parsed.hostname,
  345. )
  346.  
  347. return False
  348.  
  349. def _get_index_urls_locations(self, project_name):
  350. """Returns the locations found via self.index_urls
  351.  
  352. Checks the url_name on the main (first in the list) index and
  353. use this url_name to produce all locations
  354. """
  355.  
  356. def mkurl_pypi_url(url):
  357. loc = posixpath.join(url, project_url_name)
  358. # For maximum compatibility with easy_install, ensure the path
  359. # ends in a trailing slash. Although this isn't in the spec
  360. # (and PyPI can handle it without the slash) some other index
  361. # implementations might break if they relied on easy_install's
  362. # behavior.
  363. if not loc.endswith('/'):
  364. loc = loc + '/'
  365. return loc
  366.  
  367. project_url_name = urllib_parse.quote(project_name.lower())
  368.  
  369. if self.index_urls:
  370. # Check that we have the url_name correctly spelled:
  371.  
  372. # Only check main index if index URL is given
  373. main_index_url = Link(
  374. mkurl_pypi_url(self.index_urls[0]),
  375. trusted=True,
  376. )
  377.  
  378. page = self._get_page(main_index_url)
  379. if page is None and PyPI.netloc not in str(main_index_url):
  380. warnings.warn(
  381. "Failed to find %r at %s. It is suggested to upgrade "
  382. "your index to support normalized names as the name in "
  383. "/simple/{name}." % (project_name, main_index_url),
  384. RemovedInPip8Warning,
  385. )
  386.  
  387. project_url_name = self._find_url_name(
  388. Link(self.index_urls[0], trusted=True),
  389. project_url_name,
  390. ) or project_url_name
  391.  
  392. if project_url_name is not None:
  393. return [mkurl_pypi_url(url) for url in self.index_urls]
  394. return []
  395.  
  396. def _find_all_versions(self, project_name):
  397. """Find all available versions for project_name
  398.  
  399. This checks index_urls, find_links and dependency_links
  400. All versions found are returned
  401.  
  402. See _link_package_versions for details on which files are accepted
  403. """
  404. index_locations = self._get_index_urls_locations(project_name)
  405. index_file_loc, index_url_loc = self._sort_locations(index_locations)
  406. fl_file_loc, fl_url_loc = self._sort_locations(
  407. self.find_links, expand_dir=True)
  408. dep_file_loc, dep_url_loc = self._sort_locations(self.dependency_links)
  409.  
  410. file_locations = (
  411. Link(url) for url in itertools.chain(
  412. index_file_loc, fl_file_loc, dep_file_loc)
  413. )
  414.  
  415. # We trust every url that the user has given us whether it was given
  416. # via --index-url or --find-links
  417. # We explicitly do not trust links that came from dependency_links
  418. # We want to filter out any thing which does not have a secure origin.
  419. url_locations = [
  420. link for link in itertools.chain(
  421. (Link(url, trusted=True) for url in index_url_loc),
  422. (Link(url, trusted=True) for url in fl_url_loc),
  423. (Link(url) for url in dep_url_loc),
  424. )
  425. if self._validate_secure_origin(logger, link)
  426. ]
  427.  
  428. logger.debug('%d location(s) to search for versions of %s:',
  429. len(url_locations), project_name)
  430.  
  431. for location in url_locations:
  432. logger.debug('* %s', location)
  433.  
  434. canonical_name = pkg_resources.safe_name(project_name).lower()
  435. formats = fmt_ctl_formats(self.format_control, canonical_name)
  436. search = Search(project_name.lower(), canonical_name, formats)
  437. find_links_versions = self._package_versions(
  438. # We trust every directly linked archive in find_links
  439. (Link(url, '-f', trusted=True) for url in self.find_links),
  440. search
  441. )
  442.  
  443. page_versions = []
  444. for page in self._get_pages(url_locations, project_name):
  445. logger.debug('Analyzing links from page %s', page.url)
  446. with indent_log():
  447. page_versions.extend(
  448. self._package_versions(page.links, search)
  449. )
  450.  
  451. dependency_versions = self._package_versions(
  452. (Link(url) for url in self.dependency_links), search
  453. )
  454. if dependency_versions:
  455. logger.debug(
  456. 'dependency_links found: %s',
  457. ', '.join([
  458. version.location.url for version in dependency_versions
  459. ])
  460. )
  461.  
  462. file_versions = self._package_versions(file_locations, search)
  463. if file_versions:
  464. file_versions.sort(reverse=True)
  465. logger.debug(
  466. 'Local files found: %s',
  467. ', '.join([
  468. url_to_path(candidate.location.url)
  469. for candidate in file_versions
  470. ])
  471. )
  472.  
  473. # This is an intentional priority ordering
  474. return (
  475. file_versions + find_links_versions + page_versions +
  476. dependency_versions
  477. )
  478.  
  479. def find_requirement(self, req, upgrade):
  480. """Try to find an InstallationCandidate for req
  481.  
  482. Expects req, an InstallRequirement and upgrade, a boolean
  483. Returns an InstallationCandidate or None
  484. May raise DistributionNotFound or BestVersionAlreadyInstalled
  485. """
  486. all_versions = self._find_all_versions(req.name)
  487.  
  488. # Filter out anything which doesn't match our specifier
  489. _versions = set(
  490. req.specifier.filter(
  491. # We turn the version object into a str here because otherwise
  492. # when we're debundled but setuptools isn't, Python will see
  493. # packaging.version.Version and
  494. # pkg_resources._vendor.packaging.version.Version as different
  495. # types. This way we'll use a str as a common data interchange
  496. # format. If we stop using the pkg_resources provided specifier
  497. # and start using our own, we can drop the cast to str().
  498. [str(x.version) for x in all_versions],
  499. prereleases=(
  500. self.allow_all_prereleases
  501. if self.allow_all_prereleases else None
  502. ),
  503. )
  504. )
  505. applicable_versions = [
  506. # Again, converting to str to deal with debundling.
  507. x for x in all_versions if str(x.version) in _versions
  508. ]
  509.  
  510. if req.satisfied_by is not None:
  511. # Finally add our existing versions to the front of our versions.
  512. applicable_versions.insert(
  513. 0,
  514. InstallationCandidate(
  515. req.name,
  516. req.satisfied_by.version,
  517. INSTALLED_VERSION,
  518. )
  519. )
  520. existing_applicable = True
  521. else:
  522. existing_applicable = False
  523.  
  524. applicable_versions = self._sort_versions(applicable_versions)
  525.  
  526. if not upgrade and existing_applicable:
  527. if applicable_versions[0].location is INSTALLED_VERSION:
  528. logger.debug(
  529. 'Existing installed version (%s) is most up-to-date and '
  530. 'satisfies requirement',
  531. req.satisfied_by.version,
  532. )
  533. else:
  534. logger.debug(
  535. 'Existing installed version (%s) satisfies requirement '
  536. '(most up-to-date version is %s)',
  537. req.satisfied_by.version,
  538. applicable_versions[0][2],
  539. )
  540. return None
  541.  
  542. if not applicable_versions:
  543. logger.critical(
  544. 'Could not find a version that satisfies the requirement %s '
  545. '(from versions: %s)',
  546. req,
  547. ', '.join(
  548. sorted(
  549. set(str(i.version) for i in all_versions),
  550. key=parse_version,
  551. )
  552. )
  553. )
  554.  
  555. if self.need_warn_external:
  556. logger.warning(
  557. "Some externally hosted files were ignored as access to "
  558. "them may be unreliable (use --allow-external %s to "
  559. "allow).",
  560. req.name,
  561. )
  562.  
  563. if self.need_warn_unverified:
  564. logger.warning(
  565. "Some insecure and unverifiable files were ignored"
  566. " (use --allow-unverified %s to allow).",
  567. req.name,
  568. )
  569.  
  570. raise DistributionNotFound(
  571. 'No matching distribution found for %s' % req
  572. )
  573.  
  574. if applicable_versions[0].location is INSTALLED_VERSION:
  575. # We have an existing version, and its the best version
  576. logger.debug(
  577. 'Installed version (%s) is most up-to-date (past versions: '
  578. '%s)',
  579. req.satisfied_by.version,
  580. ', '.join(str(i.version) for i in applicable_versions[1:]) or
  581. "none",
  582. )
  583. raise BestVersionAlreadyInstalled
  584.  
  585. if len(applicable_versions) > 1:
  586. logger.debug(
  587. 'Using version %s (newest of versions: %s)',
  588. applicable_versions[0].version,
  589. ', '.join(str(i.version) for i in applicable_versions)
  590. )
  591.  
  592. selected_version = applicable_versions[0].location
  593.  
  594. if (selected_version.verifiable is not None and not
  595. selected_version.verifiable):
  596. logger.warning(
  597. "%s is potentially insecure and unverifiable.", req.name,
  598. )
  599.  
  600. return selected_version
  601.  
  602. def _find_url_name(self, index_url, url_name):
  603. """
  604. Finds the true URL name of a package, when the given name isn't quite
  605. correct.
  606. This is usually used to implement case-insensitivity.
  607. """
  608. if not index_url.url.endswith('/'):
  609. # Vaguely part of the PyPI API... weird but true.
  610. # FIXME: bad to modify this?
  611. index_url.url += '/'
  612. page = self._get_page(index_url)
  613. if page is None:
  614. logger.critical('Cannot fetch index base URL %s', index_url)
  615. return
  616. norm_name = normalize_name(url_name)
  617. for link in page.links:
  618. base = posixpath.basename(link.path.rstrip('/'))
  619. if norm_name == normalize_name(base):
  620. logger.debug(
  621. 'Real name of requirement %s is %s', url_name, base,
  622. )
  623. return base
  624. return None
  625.  
  626. def _get_pages(self, locations, project_name):
  627. """
  628. Yields (page, page_url) from the given locations, skipping
  629. locations that have errors, and adding download/homepage links
  630. """
  631. all_locations = list(locations)
  632. seen = set()
  633. normalized = normalize_name(project_name)
  634.  
  635. while all_locations:
  636. location = all_locations.pop(0)
  637. if location in seen:
  638. continue
  639. seen.add(location)
  640.  
  641. page = self._get_page(location)
  642. if page is None:
  643. continue
  644.  
  645. yield page
  646.  
  647. for link in page.rel_links():
  648.  
  649. if (normalized not in self.allow_external and not
  650. self.allow_all_external):
  651. self.need_warn_external = True
  652. logger.debug(
  653. "Not searching %s for files because external "
  654. "urls are disallowed.",
  655. link,
  656. )
  657. continue
  658.  
  659. if (link.trusted is not None and not
  660. link.trusted and
  661. normalized not in self.allow_unverified):
  662. logger.debug(
  663. "Not searching %s for urls, it is an "
  664. "untrusted link and cannot produce safe or "
  665. "verifiable files.",
  666. link,
  667. )
  668. self.need_warn_unverified = True
  669. continue
  670.  
  671. all_locations.append(link)
  672.  
  673. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  674.  
  675. def _sort_links(self, links):
  676. """
  677. Returns elements of links in order, non-egg links first, egg links
  678. second, while eliminating duplicates
  679. """
  680. eggs, no_eggs = [], []
  681. seen = set()
  682. for link in links:
  683. if link not in seen:
  684. seen.add(link)
  685. if link.egg_fragment:
  686. eggs.append(link)
  687. else:
  688. no_eggs.append(link)
  689. return no_eggs + eggs
  690.  
  691. def _package_versions(self, links, search):
  692. result = []
  693. for link in self._sort_links(links):
  694. v = self._link_package_versions(link, search)
  695. if v is not None:
  696. result.append(v)
  697. return result
  698.  
  699. def _log_skipped_link(self, link, reason):
  700. if link not in self.logged_links:
  701. logger.debug('Skipping link %s; %s', link, reason)
  702. self.logged_links.add(link)
  703.  
  704. def _link_package_versions(self, link, search):
  705. """Return an InstallationCandidate or None"""
  706. platform = get_platform()
  707.  
  708. version = None
  709. if link.egg_fragment:
  710. egg_info = link.egg_fragment
  711. ext = link.ext
  712. else:
  713. egg_info, ext = link.splitext()
  714. if not ext:
  715. self._log_skipped_link(link, 'not a file')
  716. return
  717. if ext not in SUPPORTED_EXTENSIONS:
  718. self._log_skipped_link(
  719. link, 'unsupported archive format: %s' % ext)
  720. return
  721. if "binary" not in search.formats and ext == wheel_ext:
  722. self._log_skipped_link(
  723. link, 'No binaries permitted for %s' % search.supplied)
  724. return
  725. if "macosx10" in link.path and ext == '.zip':
  726. self._log_skipped_link(link, 'macosx10 one')
  727. return
  728. if ext == wheel_ext:
  729. try:
  730. wheel = Wheel(link.filename)
  731. except InvalidWheelFilename:
  732. self._log_skipped_link(link, 'invalid wheel filename')
  733. return
  734. if (pkg_resources.safe_name(wheel.name).lower() !=
  735. search.canonical):
  736. self._log_skipped_link(
  737. link, 'wrong project name (not %s)' % search.supplied)
  738. return
  739. if not wheel.supported():
  740. self._log_skipped_link(
  741. link, 'it is not compatible with this Python')
  742. return
  743. # This is a dirty hack to prevent installing Binary Wheels from
  744. # PyPI unless it is a Windows or Mac Binary Wheel. This is
  745. # paired with a change to PyPI disabling uploads for the
  746. # same. Once we have a mechanism for enabling support for
  747. # binary wheels on linux that deals with the inherent problems
  748. # of binary distribution this can be removed.
  749. comes_from = getattr(link, "comes_from", None)
  750. if (
  751. (
  752. not platform.startswith('win') and not
  753. platform.startswith('macosx') and not
  754. platform == 'cli'
  755. ) and
  756. comes_from is not None and
  757. urllib_parse.urlparse(
  758. comes_from.url
  759. ).netloc.endswith(PyPI.netloc)):
  760. if not wheel.supported(tags=supported_tags_noarch):
  761. self._log_skipped_link(
  762. link,
  763. "it is a pypi-hosted binary "
  764. "Wheel on an unsupported platform",
  765. )
  766. return
  767. version = wheel.version
  768.  
  769. # This should be up by the search.ok_binary check, but see issue 2700.
  770. if "source" not in search.formats and ext != wheel_ext:
  771. self._log_skipped_link(
  772. link, 'No sources permitted for %s' % search.supplied)
  773. return
  774.  
  775. if not version:
  776. version = egg_info_matches(egg_info, search.supplied, link)
  777. if version is None:
  778. self._log_skipped_link(
  779. link, 'wrong project name (not %s)' % search.supplied)
  780. return
  781.  
  782. if (link.internal is not None and not
  783. link.internal and not
  784. normalize_name(search.supplied).lower()
  785. in self.allow_external and not
  786. self.allow_all_external):
  787. # We have a link that we are sure is external, so we should skip
  788. # it unless we are allowing externals
  789. self._log_skipped_link(link, 'it is externally hosted')
  790. self.need_warn_external = True
  791. return
  792.  
  793. if (link.verifiable is not None and not
  794. link.verifiable and not
  795. (normalize_name(search.supplied).lower()
  796. in self.allow_unverified)):
  797. # We have a link that we are sure we cannot verify its integrity,
  798. # so we should skip it unless we are allowing unsafe installs
  799. # for this requirement.
  800. self._log_skipped_link(
  801. link, 'it is an insecure and unverifiable file')
  802. self.need_warn_unverified = True
  803. return
  804.  
  805. match = self._py_version_re.search(version)
  806. if match:
  807. version = version[:match.start()]
  808. py_version = match.group(1)
  809. if py_version != sys.version[:3]:
  810. self._log_skipped_link(
  811. link, 'Python version is incorrect')
  812. return
  813. logger.debug('Found link %s, version: %s', link, version)
  814.  
  815. return InstallationCandidate(search.supplied, version, link)
  816.  
  817. def _get_page(self, link):
  818. return HTMLPage.get_page(link, session=self.session)
  819.  
  820.  
  821. def egg_info_matches(
  822. egg_info, search_name, link,
  823. _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)):
  824. """Pull the version part out of a string.
  825.  
  826. :param egg_info: The string to parse. E.g. foo-2.1
  827. :param search_name: The name of the package this belongs to. None to
  828. infer the name. Note that this cannot unambiguously parse strings
  829. like foo-2-2 which might be foo, 2-2 or foo-2, 2.
  830. :param link: The link the string came from, for logging on failure.
  831. """
  832. match = _egg_info_re.search(egg_info)
  833. if not match:
  834. logger.debug('Could not parse version from link: %s', link)
  835. return None
  836. if search_name is None:
  837. full_match = match.group(0)
  838. return full_match[full_match.index('-'):]
  839. name = match.group(0).lower()
  840. # To match the "safe" name that pkg_resources creates:
  841. name = name.replace('_', '-')
  842. # project name and version must be separated by a dash
  843. look_for = search_name.lower() + "-"
  844. if name.startswith(look_for):
  845. return match.group(0)[len(look_for):]
  846. else:
  847. return None
  848.  
  849.  
  850. class HTMLPage(object):
  851. """Represents one page, along with its URL"""
  852.  
  853. def __init__(self, content, url, headers=None, trusted=None):
  854. # Determine if we have any encoding information in our headers
  855. encoding = None
  856. if headers and "Content-Type" in headers:
  857. content_type, params = cgi.parse_header(headers["Content-Type"])
  858.  
  859. if "charset" in params:
  860. encoding = params['charset']
  861.  
  862. self.content = content
  863. self.parsed = html5lib.parse(
  864. self.content,
  865. encoding=encoding,
  866. namespaceHTMLElements=False,
  867. )
  868. self.url = url
  869. self.headers = headers
  870. self.trusted = trusted
  871.  
  872. def __str__(self):
  873. return self.url
  874.  
  875. @classmethod
  876. def get_page(cls, link, skip_archives=True, session=None):
  877. if session is None:
  878. raise TypeError(
  879. "get_page() missing 1 required keyword argument: 'session'"
  880. )
  881.  
  882. url = link.url
  883. url = url.split('#', 1)[0]
  884.  
  885. # Check for VCS schemes that do not support lookup as web pages.
  886. from pip.vcs import VcsSupport
  887. for scheme in VcsSupport.schemes:
  888. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  889. logger.debug('Cannot look at %s URL %s', scheme, link)
  890. return None
  891.  
  892. try:
  893. if skip_archives:
  894. filename = link.filename
  895. for bad_ext in ARCHIVE_EXTENSIONS:
  896. if filename.endswith(bad_ext):
  897. content_type = cls._get_content_type(
  898. url, session=session,
  899. )
  900. if content_type.lower().startswith('text/html'):
  901. break
  902. else:
  903. logger.debug(
  904. 'Skipping page %s because of Content-Type: %s',
  905. link,
  906. content_type,
  907. )
  908. return
  909.  
  910. logger.debug('Getting page %s', url)
  911.  
  912. # Tack index.html onto file:// URLs that point to directories
  913. (scheme, netloc, path, params, query, fragment) = \
  914. urllib_parse.urlparse(url)
  915. if (scheme == 'file' and
  916. os.path.isdir(urllib_request.url2pathname(path))):
  917. # add trailing slash if not present so urljoin doesn't trim
  918. # final segment
  919. if not url.endswith('/'):
  920. url += '/'
  921. url = urllib_parse.urljoin(url, 'index.html')
  922. logger.debug(' file: URL is directory, getting %s', url)
  923.  
  924. resp = session.get(
  925. url,
  926. headers={
  927. "Accept": "text/html",
  928. "Cache-Control": "max-age=600",
  929. },
  930. )
  931. resp.raise_for_status()
  932.  
  933. # The check for archives above only works if the url ends with
  934. # something that looks like an archive. However that is not a
  935. # requirement of an url. Unless we issue a HEAD request on every
  936. # url we cannot know ahead of time for sure if something is HTML
  937. # or not. However we can check after we've downloaded it.
  938. content_type = resp.headers.get('Content-Type', 'unknown')
  939. if not content_type.lower().startswith("text/html"):
  940. logger.debug(
  941. 'Skipping page %s because of Content-Type: %s',
  942. link,
  943. content_type,
  944. )
  945. return
  946.  
  947. inst = cls(
  948. resp.content, resp.url, resp.headers,
  949. trusted=link.trusted,
  950. )
  951. except requests.HTTPError as exc:
  952. level = 2 if exc.response.status_code == 404 else 1
  953. cls._handle_fail(link, exc, url, level=level)
  954. except requests.ConnectionError as exc:
  955. cls._handle_fail(link, "connection error: %s" % exc, url)
  956. except requests.Timeout:
  957. cls._handle_fail(link, "timed out", url)
  958. except SSLError as exc:
  959. reason = ("There was a problem confirming the ssl certificate: "
  960. "%s" % exc)
  961. cls._handle_fail(link, reason, url, level=2, meth=logger.info)
  962. else:
  963. return inst
  964.  
  965. @staticmethod
  966. def _handle_fail(link, reason, url, level=1, meth=None):
  967. if meth is None:
  968. meth = logger.debug
  969.  
  970. meth("Could not fetch URL %s: %s - skipping", link, reason)
  971.  
  972. @staticmethod
  973. def _get_content_type(url, session):
  974. """Get the Content-Type of the given url, using a HEAD request"""
  975. scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
  976. if scheme not in ('http', 'https'):
  977. # FIXME: some warning or something?
  978. # assertion error?
  979. return ''
  980.  
  981. resp = session.head(url, allow_redirects=True)
  982. resp.raise_for_status()
  983.  
  984. return resp.headers.get("Content-Type", "")
  985.  
  986. @cached_property
  987. def api_version(self):
  988. metas = [
  989. x for x in self.parsed.findall(".//meta")
  990. if x.get("name", "").lower() == "api-version"
  991. ]
  992. if metas:
  993. try:
  994. return int(metas[0].get("value", None))
  995. except (TypeError, ValueError):
  996. pass
  997.  
  998. return None
  999.  
  1000. @cached_property
  1001. def base_url(self):
  1002. bases = [
  1003. x for x in self.parsed.findall(".//base")
  1004. if x.get("href") is not None
  1005. ]
  1006. if bases and bases[0].get("href"):
  1007. return bases[0].get("href")
  1008. else:
  1009. return self.url
  1010.  
  1011. @property
  1012. def links(self):
  1013. """Yields all links in the page"""
  1014. for anchor in self.parsed.findall(".//a"):
  1015. if anchor.get("href"):
  1016. href = anchor.get("href")
  1017. url = self.clean_link(
  1018. urllib_parse.urljoin(self.base_url, href)
  1019. )
  1020.  
  1021. # Determine if this link is internal. If that distinction
  1022. # doesn't make sense in this context, then we don't make
  1023. # any distinction.
  1024. internal = None
  1025. if self.api_version and self.api_version >= 2:
  1026. # Only api_versions >= 2 have a distinction between
  1027. # external and internal links
  1028. internal = bool(
  1029. anchor.get("rel") and
  1030. "internal" in anchor.get("rel").split()
  1031. )
  1032.  
  1033. yield Link(url, self, internal=internal)
  1034.  
  1035. def rel_links(self, rels=('homepage', 'download')):
  1036. """Yields all links with the given relations"""
  1037. rels = set(rels)
  1038.  
  1039. for anchor in self.parsed.findall(".//a"):
  1040. if anchor.get("rel") and anchor.get("href"):
  1041. found_rels = set(anchor.get("rel").split())
  1042. # Determine the intersection between what rels were found and
  1043. # what rels were being looked for
  1044. if found_rels & rels:
  1045. href = anchor.get("href")
  1046. url = self.clean_link(
  1047. urllib_parse.urljoin(self.base_url, href)
  1048. )
  1049. yield Link(url, self, trusted=False)
  1050.  
  1051. _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
  1052.  
  1053. def clean_link(self, url):
  1054. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  1055. the link, it will be rewritten to %20 (while not over-quoting
  1056. % or other characters)."""
  1057. return self._clean_re.sub(
  1058. lambda match: '%%%2x' % ord(match.group(0)), url)
  1059.  
  1060.  
  1061. class Link(object):
  1062.  
  1063. def __init__(self, url, comes_from=None, internal=None, trusted=None):
  1064.  
  1065. # url can be a UNC windows share
  1066. if url != Inf and url.startswith('\\\\'):
  1067. url = path_to_url(url)
  1068.  
  1069. self.url = url
  1070. self.comes_from = comes_from
  1071. self.internal = internal
  1072. self.trusted = trusted
  1073.  
  1074. def __str__(self):
  1075. if self.comes_from:
  1076. return '%s (from %s)' % (self.url, self.comes_from)
  1077. else:
  1078. return str(self.url)
  1079.  
  1080. def __repr__(self):
  1081. return '<Link %s>' % self
  1082.  
  1083. def __eq__(self, other):
  1084. if not isinstance(other, Link):
  1085. return NotImplemented
  1086. return self.url == other.url
  1087.  
  1088. def __ne__(self, other):
  1089. if not isinstance(other, Link):
  1090. return NotImplemented
  1091. return self.url != other.url
  1092.  
  1093. def __lt__(self, other):
  1094. if not isinstance(other, Link):
  1095. return NotImplemented
  1096. return self.url < other.url
  1097.  
  1098. def __le__(self, other):
  1099. if not isinstance(other, Link):
  1100. return NotImplemented
  1101. return self.url <= other.url
  1102.  
  1103. def __gt__(self, other):
  1104. if not isinstance(other, Link):
  1105. return NotImplemented
  1106. return self.url > other.url
  1107.  
  1108. def __ge__(self, other):
  1109. if not isinstance(other, Link):
  1110. return NotImplemented
  1111. return self.url >= other.url
  1112.  
  1113. def __hash__(self):
  1114. return hash(self.url)
  1115.  
  1116. @property
  1117. def filename(self):
  1118. _, netloc, path, _, _ = urllib_parse.urlsplit(self.url)
  1119. name = posixpath.basename(path.rstrip('/')) or netloc
  1120. name = urllib_parse.unquote(name)
  1121. assert name, ('URL %r produced no filename' % self.url)
  1122. return name
  1123.  
  1124. @property
  1125. def scheme(self):
  1126. return urllib_parse.urlsplit(self.url)[0]
  1127.  
  1128. @property
  1129. def netloc(self):
  1130. return urllib_parse.urlsplit(self.url)[1]
  1131.  
  1132. @property
  1133. def path(self):
  1134. return urllib_parse.unquote(urllib_parse.urlsplit(self.url)[2])
  1135.  
  1136. def splitext(self):
  1137. return splitext(posixpath.basename(self.path.rstrip('/')))
  1138.  
  1139. @property
  1140. def ext(self):
  1141. return self.splitext()[1]
  1142.  
  1143. @property
  1144. def url_without_fragment(self):
  1145. scheme, netloc, path, query, fragment = urllib_parse.urlsplit(self.url)
  1146. return urllib_parse.urlunsplit((scheme, netloc, path, query, None))
  1147.  
  1148. _egg_fragment_re = re.compile(r'#egg=([^&]*)')
  1149.  
  1150. @property
  1151. def egg_fragment(self):
  1152. match = self._egg_fragment_re.search(self.url)
  1153. if not match:
  1154. return None
  1155. return match.group(1)
  1156.  
  1157. _hash_re = re.compile(
  1158. r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)'
  1159. )
  1160.  
  1161. @property
  1162. def hash(self):
  1163. match = self._hash_re.search(self.url)
  1164. if match:
  1165. return match.group(2)
  1166. return None
  1167.  
  1168. @property
  1169. def hash_name(self):
  1170. match = self._hash_re.search(self.url)
  1171. if match:
  1172. return match.group(1)
  1173. return None
  1174.  
  1175. @property
  1176. def show_url(self):
  1177. return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0])
  1178.  
  1179. @property
  1180. def verifiable(self):
  1181. """
  1182. Returns True if this link can be verified after download, False if it
  1183. cannot, and None if we cannot determine.
  1184. """
  1185. trusted = self.trusted or getattr(self.comes_from, "trusted", None)
  1186. if trusted is not None and trusted:
  1187. # This link came from a trusted source. It *may* be verifiable but
  1188. # first we need to see if this page is operating under the new
  1189. # API version.
  1190. try:
  1191. api_version = getattr(self.comes_from, "api_version", None)
  1192. api_version = int(api_version)
  1193. except (ValueError, TypeError):
  1194. api_version = None
  1195.  
  1196. if api_version is None or api_version <= 1:
  1197. # This link is either trusted, or it came from a trusted,
  1198. # however it is not operating under the API version 2 so
  1199. # we can't make any claims about if it's safe or not
  1200. return
  1201.  
  1202. if self.hash:
  1203. # This link came from a trusted source and it has a hash, so we
  1204. # can consider it safe.
  1205. return True
  1206. else:
  1207. # This link came from a trusted source, using the new API
  1208. # version, and it does not have a hash. It is NOT verifiable
  1209. return False
  1210. elif trusted is not None:
  1211. # This link came from an untrusted source and we cannot trust it
  1212. return False
  1213.  
  1214. @property
  1215. def is_wheel(self):
  1216. return self.ext == wheel_ext
  1217.  
  1218. @property
  1219. def is_artifact(self):
  1220. """
  1221. Determines if this points to an actual artifact (e.g. a tarball) or if
  1222. it points to an "abstract" thing like a path or a VCS location.
  1223. """
  1224. from pip.vcs import vcs
  1225.  
  1226. if self.scheme in vcs.all_schemes:
  1227. return False
  1228.  
  1229. return True
  1230.  
  1231.  
  1232. # An object to represent the "link" for the installed version of a requirement.
  1233. # Using Inf as the url makes it sort higher.
  1234. INSTALLED_VERSION = Link(Inf)
  1235.  
  1236.  
  1237. FormatControl = namedtuple('FormatControl', 'no_binary only_binary')
  1238. """This object has two fields, no_binary and only_binary.
  1239.  
  1240. If a field is falsy, it isn't set. If it is {':all:'}, it should match all
  1241. packages except those listed in the other field. Only one field can be set
  1242. to {':all:'} at a time. The rest of the time exact package name matches
  1243. are listed, with any given package only showing up in one field at a time.
  1244. """
  1245.  
  1246.  
  1247. def fmt_ctl_handle_mutual_exclude(value, target, other):
  1248. new = value.split(',')
  1249. while ':all:' in new:
  1250. other.clear()
  1251. target.clear()
  1252. target.add(':all:')
  1253. del new[:new.index(':all:') + 1]
  1254. if ':none:' not in new:
  1255. # Without a none, we want to discard everything as :all: covers it
  1256. return
  1257. for name in new:
  1258. if name == ':none:':
  1259. target.clear()
  1260. continue
  1261. name = pkg_resources.safe_name(name).lower()
  1262. other.discard(name)
  1263. target.add(name)
  1264.  
  1265.  
  1266. def fmt_ctl_formats(fmt_ctl, canonical_name):
  1267. result = set(["binary", "source"])
  1268. if canonical_name in fmt_ctl.only_binary:
  1269. result.discard('source')
  1270. elif canonical_name in fmt_ctl.no_binary:
  1271. result.discard('binary')
  1272. elif ':all:' in fmt_ctl.only_binary:
  1273. result.discard('source')
  1274. elif ':all:' in fmt_ctl.no_binary:
  1275. result.discard('binary')
  1276. return frozenset(result)
  1277.  
  1278.  
  1279. def fmt_ctl_no_binary(fmt_ctl):
  1280. fmt_ctl_handle_mutual_exclude(
  1281. ':all:', fmt_ctl.no_binary, fmt_ctl.only_binary)
  1282.  
  1283.  
  1284. def fmt_ctl_no_use_wheel(fmt_ctl):
  1285. fmt_ctl_no_binary(fmt_ctl)
  1286. warnings.warn(
  1287. '--no-use-wheel is deprecated and will be removed in the future. '
  1288. ' Please use --no-binary :all: instead.', DeprecationWarning,
  1289. stacklevel=2)
  1290.  
  1291.  
  1292. Search = namedtuple('Search', 'supplied canonical formats')
  1293. """Capture key aspects of a search.
  1294.  
  1295. :attribute supplied: The user supplied package.
  1296. :attribute canonical: The canonical package name.
  1297. :attribute formats: The formats allowed for this package. Should be a set
  1298. with 'binary' or 'source' or both in it.
  1299. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement