index.py 45 KB

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