index.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. """Routines related to PyPI, indexes"""
  2. import sys
  3. import os
  4. import re
  5. import mimetypes
  6. import posixpath
  7. from pip.log import logger
  8. from pip.util import Inf, normalize_name, splitext, is_prerelease
  9. from pip.exceptions import (DistributionNotFound, BestVersionAlreadyInstalled,
  10. InstallationError, InvalidWheelFilename, UnsupportedWheel)
  11. from pip.backwardcompat import urlparse, url2pathname
  12. from pip.download import PipSession, url_to_path, path_to_url
  13. from pip.wheel import Wheel, wheel_ext
  14. from pip.pep425tags import supported_tags, supported_tags_noarch, get_platform
  15. from pip._vendor import html5lib, requests, pkg_resources
  16. from pip._vendor.requests.exceptions import SSLError
  17. __all__ = ['PackageFinder']
  18. DEFAULT_MIRROR_HOSTNAME = "last.pypi.python.org"
  19. INSECURE_SCHEMES = {
  20. "http": ["https"],
  21. }
  22. class PackageFinder(object):
  23. """This finds packages.
  24. This is meant to match easy_install's technique for looking for
  25. packages, by reading pages and looking for appropriate links
  26. """
  27. def __init__(self, find_links, index_urls,
  28. use_wheel=True, allow_external=[], allow_unverified=[],
  29. allow_all_external=False, allow_all_prereleases=False,
  30. process_dependency_links=False, session=None):
  31. self.find_links = find_links
  32. self.index_urls = index_urls
  33. self.dependency_links = []
  34. self.cache = PageCache()
  35. # These are boring links that have already been logged somehow:
  36. self.logged_links = set()
  37. self.use_wheel = use_wheel
  38. # Do we allow (safe and verifiable) externally hosted files?
  39. self.allow_external = set(normalize_name(n) for n in allow_external)
  40. # Which names are allowed to install insecure and unverifiable files?
  41. self.allow_unverified = set(
  42. normalize_name(n) for n in allow_unverified
  43. )
  44. # Anything that is allowed unverified is also allowed external
  45. self.allow_external |= self.allow_unverified
  46. # Do we allow all (safe and verifiable) externally hosted files?
  47. self.allow_all_external = allow_all_external
  48. # Stores if we ignored any external links so that we can instruct
  49. # end users how to install them if no distributions are available
  50. self.need_warn_external = False
  51. # Stores if we ignored any unsafe links so that we can instruct
  52. # end users how to install them if no distributions are available
  53. self.need_warn_unverified = False
  54. # Do we want to allow _all_ pre-releases?
  55. self.allow_all_prereleases = allow_all_prereleases
  56. # Do we process dependency links?
  57. self.process_dependency_links = process_dependency_links
  58. self._have_warned_dependency_links = False
  59. # The Session we'll use to make requests
  60. self.session = session or PipSession()
  61. def add_dependency_links(self, links):
  62. ## FIXME: this shouldn't be global list this, it should only
  63. ## apply to requirements of the package that specifies the
  64. ## dependency_links value
  65. ## FIXME: also, we should track comes_from (i.e., use Link)
  66. if self.process_dependency_links:
  67. if not self._have_warned_dependency_links:
  68. logger.deprecated(
  69. "1.6",
  70. "Dependency Links processing has been deprecated with an "
  71. "accelerated time schedule and will be removed in pip 1.6",
  72. )
  73. self._have_warned_dependency_links = True
  74. self.dependency_links.extend(links)
  75. def _sort_locations(self, locations):
  76. """
  77. Sort locations into "files" (archives) and "urls", and return
  78. a pair of lists (files,urls)
  79. """
  80. files = []
  81. urls = []
  82. # puts the url for the given file path into the appropriate list
  83. def sort_path(path):
  84. url = path_to_url(path)
  85. if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
  86. urls.append(url)
  87. else:
  88. files.append(url)
  89. for url in locations:
  90. is_local_path = os.path.exists(url)
  91. is_file_url = url.startswith('file:')
  92. is_find_link = url in self.find_links
  93. if is_local_path or is_file_url:
  94. if is_local_path:
  95. path = url
  96. else:
  97. path = url_to_path(url)
  98. if is_find_link and os.path.isdir(path):
  99. path = os.path.realpath(path)
  100. for item in os.listdir(path):
  101. sort_path(os.path.join(path, item))
  102. elif is_file_url and os.path.isdir(path):
  103. urls.append(url)
  104. elif os.path.isfile(path):
  105. sort_path(path)
  106. else:
  107. urls.append(url)
  108. return files, urls
  109. def _link_sort_key(self, link_tuple):
  110. """
  111. Function used to generate link sort key for link tuples.
  112. The greater the return value, the more preferred it is.
  113. If not finding wheels, then sorted by version only.
  114. If finding wheels, then the sort order is by version, then:
  115. 1. existing installs
  116. 2. wheels ordered via Wheel.support_index_min()
  117. 3. source archives
  118. Note: it was considered to embed this logic into the Link
  119. comparison operators, but then different sdist links
  120. with the same version, would have to be considered equal
  121. """
  122. parsed_version, link, _ = link_tuple
  123. if self.use_wheel:
  124. support_num = len(supported_tags)
  125. if link == INSTALLED_VERSION:
  126. pri = 1
  127. elif link.ext == wheel_ext:
  128. wheel = Wheel(link.filename) # can raise InvalidWheelFilename
  129. if not wheel.supported():
  130. raise UnsupportedWheel("%s is not a supported wheel for this platform. It can't be sorted." % wheel.filename)
  131. pri = -(wheel.support_index_min())
  132. else: # sdist
  133. pri = -(support_num)
  134. return (parsed_version, pri)
  135. else:
  136. return parsed_version
  137. def _sort_versions(self, applicable_versions):
  138. """
  139. Bring the latest version (and wheels) to the front, but maintain the existing ordering as secondary.
  140. See the docstring for `_link_sort_key` for details.
  141. This function is isolated for easier unit testing.
  142. """
  143. return sorted(applicable_versions, key=self._link_sort_key, reverse=True)
  144. def find_requirement(self, req, upgrade):
  145. def mkurl_pypi_url(url):
  146. loc = posixpath.join(url, url_name)
  147. # For maximum compatibility with easy_install, ensure the path
  148. # ends in a trailing slash. Although this isn't in the spec
  149. # (and PyPI can handle it without the slash) some other index
  150. # implementations might break if they relied on easy_install's behavior.
  151. if not loc.endswith('/'):
  152. loc = loc + '/'
  153. return loc
  154. url_name = req.url_name
  155. # Only check main index if index URL is given:
  156. main_index_url = None
  157. if self.index_urls:
  158. # Check that we have the url_name correctly spelled:
  159. main_index_url = Link(mkurl_pypi_url(self.index_urls[0]), trusted=True)
  160. # This will also cache the page, so it's okay that we get it again later:
  161. page = self._get_page(main_index_url, req)
  162. if page is None:
  163. url_name = self._find_url_name(Link(self.index_urls[0], trusted=True), url_name, req) or req.url_name
  164. if url_name is not None:
  165. locations = [
  166. mkurl_pypi_url(url)
  167. for url in self.index_urls] + self.find_links
  168. else:
  169. locations = list(self.find_links)
  170. for version in req.absolute_versions:
  171. if url_name is not None and main_index_url is not None:
  172. locations = [
  173. posixpath.join(main_index_url.url, version)] + locations
  174. file_locations, url_locations = self._sort_locations(locations)
  175. _flocations, _ulocations = self._sort_locations(self.dependency_links)
  176. file_locations.extend(_flocations)
  177. # We trust every url that the user has given us whether it was given
  178. # via --index-url or --find-links
  179. locations = [Link(url, trusted=True) for url in url_locations]
  180. # We explicitly do not trust links that came from dependency_links
  181. locations.extend([Link(url) for url in _ulocations])
  182. logger.debug('URLs to search for versions for %s:' % req)
  183. for location in locations:
  184. logger.debug('* %s' % location)
  185. # Determine if this url used a secure transport mechanism
  186. parsed = urlparse.urlparse(str(location))
  187. if parsed.scheme in INSECURE_SCHEMES:
  188. secure_schemes = INSECURE_SCHEMES[parsed.scheme]
  189. if len(secure_schemes) == 1:
  190. ctx = (location, parsed.scheme, secure_schemes[0],
  191. parsed.netloc)
  192. logger.warn("%s uses an insecure transport scheme (%s). "
  193. "Consider using %s if %s has it available" %
  194. ctx)
  195. elif len(secure_schemes) > 1:
  196. ctx = (location, parsed.scheme, ", ".join(secure_schemes),
  197. parsed.netloc)
  198. logger.warn("%s uses an insecure transport scheme (%s). "
  199. "Consider using one of %s if %s has any of "
  200. "them available" % ctx)
  201. else:
  202. ctx = (location, parsed.scheme)
  203. logger.warn("%s uses an insecure transport scheme (%s)." %
  204. ctx)
  205. found_versions = []
  206. found_versions.extend(
  207. self._package_versions(
  208. # We trust every directly linked archive in find_links
  209. [Link(url, '-f', trusted=True) for url in self.find_links], req.name.lower()))
  210. page_versions = []
  211. for page in self._get_pages(locations, req):
  212. logger.debug('Analyzing links from page %s' % page.url)
  213. logger.indent += 2
  214. try:
  215. page_versions.extend(self._package_versions(page.links, req.name.lower()))
  216. finally:
  217. logger.indent -= 2
  218. dependency_versions = list(self._package_versions(
  219. [Link(url) for url in self.dependency_links], req.name.lower()))
  220. if dependency_versions:
  221. logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
  222. file_versions = list(self._package_versions(
  223. [Link(url) for url in file_locations], req.name.lower()))
  224. if not found_versions and not page_versions and not dependency_versions and not file_versions:
  225. logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
  226. if self.need_warn_external:
  227. logger.warn("Some externally hosted files were ignored (use "
  228. "--allow-external %s to allow)." % req.name)
  229. if self.need_warn_unverified:
  230. logger.warn("Some insecure and unverifiable files were ignored"
  231. " (use --allow-unverified %s to allow)." %
  232. req.name)
  233. raise DistributionNotFound('No distributions at all found for %s' % req)
  234. installed_version = []
  235. if req.satisfied_by is not None:
  236. installed_version = [(req.satisfied_by.parsed_version, INSTALLED_VERSION, req.satisfied_by.version)]
  237. if file_versions:
  238. file_versions.sort(reverse=True)
  239. logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions]))
  240. #this is an intentional priority ordering
  241. all_versions = installed_version + file_versions + found_versions + page_versions + dependency_versions
  242. applicable_versions = []
  243. for (parsed_version, link, version) in all_versions:
  244. if version not in req.req:
  245. logger.info("Ignoring link %s, version %s doesn't match %s"
  246. % (link, version, ','.join([''.join(s) for s in req.req.specs])))
  247. continue
  248. elif is_prerelease(version) and not (self.allow_all_prereleases or req.prereleases):
  249. # If this version isn't the already installed one, then
  250. # ignore it if it's a pre-release.
  251. if link is not INSTALLED_VERSION:
  252. logger.info("Ignoring link %s, version %s is a pre-release (use --pre to allow)." % (link, version))
  253. continue
  254. applicable_versions.append((parsed_version, link, version))
  255. applicable_versions = self._sort_versions(applicable_versions)
  256. existing_applicable = bool([link for parsed_version, link, version in applicable_versions if link is INSTALLED_VERSION])
  257. if not upgrade and existing_applicable:
  258. if applicable_versions[0][1] is INSTALLED_VERSION:
  259. logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
  260. % req.satisfied_by.version)
  261. else:
  262. logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
  263. % (req.satisfied_by.version, applicable_versions[0][2]))
  264. return None
  265. if not applicable_versions:
  266. logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
  267. % (req, ', '.join([version for parsed_version, link, version in all_versions])))
  268. if self.need_warn_external:
  269. logger.warn("Some externally hosted files were ignored (use "
  270. "--allow-external to allow).")
  271. if self.need_warn_unverified:
  272. logger.warn("Some insecure and unverifiable files were ignored"
  273. " (use --allow-unverified %s to allow)." %
  274. req.name)
  275. raise DistributionNotFound('No distributions matching the version for %s' % req)
  276. if applicable_versions[0][1] is INSTALLED_VERSION:
  277. # We have an existing version, and its the best version
  278. logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
  279. % (req.satisfied_by.version, ', '.join([version for parsed_version, link, version in applicable_versions[1:]]) or 'none'))
  280. raise BestVersionAlreadyInstalled
  281. if len(applicable_versions) > 1:
  282. logger.info('Using version %s (newest of versions: %s)' %
  283. (applicable_versions[0][2], ', '.join([version for parsed_version, link, version in applicable_versions])))
  284. selected_version = applicable_versions[0][1]
  285. if (selected_version.internal is not None
  286. and not selected_version.internal):
  287. logger.warn("%s an externally hosted file and may be "
  288. "unreliable" % req.name)
  289. if (selected_version.verifiable is not None
  290. and not selected_version.verifiable):
  291. logger.warn("%s is potentially insecure and "
  292. "unverifiable." % req.name)
  293. if selected_version._deprecated_regex:
  294. logger.deprecated(
  295. "1.7",
  296. "%s discovered using a deprecated method of parsing, "
  297. "in the future it will no longer be discovered" % req.name
  298. )
  299. return selected_version
  300. def _find_url_name(self, index_url, url_name, req):
  301. """Finds the true URL name of a package, when the given name isn't quite correct.
  302. This is usually used to implement case-insensitivity."""
  303. if not index_url.url.endswith('/'):
  304. # Vaguely part of the PyPI API... weird but true.
  305. ## FIXME: bad to modify this?
  306. index_url.url += '/'
  307. page = self._get_page(index_url, req)
  308. if page is None:
  309. logger.fatal('Cannot fetch index base URL %s' % index_url)
  310. return
  311. norm_name = normalize_name(req.url_name)
  312. for link in page.links:
  313. base = posixpath.basename(link.path.rstrip('/'))
  314. if norm_name == normalize_name(base):
  315. logger.notify('Real name of requirement %s is %s' % (url_name, base))
  316. return base
  317. return None
  318. def _get_pages(self, locations, req):
  319. """
  320. Yields (page, page_url) from the given locations, skipping
  321. locations that have errors, and adding download/homepage links
  322. """
  323. all_locations = list(locations)
  324. seen = set()
  325. while all_locations:
  326. location = all_locations.pop(0)
  327. if location in seen:
  328. continue
  329. seen.add(location)
  330. page = self._get_page(location, req)
  331. if page is None:
  332. continue
  333. yield page
  334. for link in page.rel_links():
  335. normalized = normalize_name(req.name).lower()
  336. if (not normalized in self.allow_external
  337. and not self.allow_all_external):
  338. self.need_warn_external = True
  339. logger.debug("Not searching %s for files because external "
  340. "urls are disallowed." % link)
  341. continue
  342. if (link.trusted is not None
  343. and not link.trusted
  344. and not normalized in self.allow_unverified):
  345. logger.debug("Not searching %s for urls, it is an "
  346. "untrusted link and cannot produce safe or "
  347. "verifiable files." % link)
  348. self.need_warn_unverified = True
  349. continue
  350. all_locations.append(link)
  351. _egg_fragment_re = re.compile(r'#egg=([^&]*)')
  352. _egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.-]+)', re.I)
  353. _py_version_re = re.compile(r'-py([123]\.?[0-9]?)$')
  354. def _sort_links(self, links):
  355. "Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates"
  356. eggs, no_eggs = [], []
  357. seen = set()
  358. for link in links:
  359. if link not in seen:
  360. seen.add(link)
  361. if link.egg_fragment:
  362. eggs.append(link)
  363. else:
  364. no_eggs.append(link)
  365. return no_eggs + eggs
  366. def _package_versions(self, links, search_name):
  367. for link in self._sort_links(links):
  368. for v in self._link_package_versions(link, search_name):
  369. yield v
  370. def _known_extensions(self):
  371. extensions = ('.tar.gz', '.tar.bz2', '.tar', '.tgz', '.zip')
  372. if self.use_wheel:
  373. return extensions + (wheel_ext,)
  374. return extensions
  375. def _link_package_versions(self, link, search_name):
  376. """
  377. Return an iterable of triples (pkg_resources_version_key,
  378. link, python_version) that can be extracted from the given
  379. link.
  380. Meant to be overridden by subclasses, not called by clients.
  381. """
  382. platform = get_platform()
  383. version = None
  384. if link.egg_fragment:
  385. egg_info = link.egg_fragment
  386. else:
  387. egg_info, ext = link.splitext()
  388. if not ext:
  389. if link not in self.logged_links:
  390. logger.debug('Skipping link %s; not a file' % link)
  391. self.logged_links.add(link)
  392. return []
  393. if egg_info.endswith('.tar'):
  394. # Special double-extension case:
  395. egg_info = egg_info[:-4]
  396. ext = '.tar' + ext
  397. if ext not in self._known_extensions():
  398. if link not in self.logged_links:
  399. logger.debug('Skipping link %s; unknown archive format: %s' % (link, ext))
  400. self.logged_links.add(link)
  401. return []
  402. if "macosx10" in link.path and ext == '.zip':
  403. if link not in self.logged_links:
  404. logger.debug('Skipping link %s; macosx10 one' % (link))
  405. self.logged_links.add(link)
  406. return []
  407. if ext == wheel_ext:
  408. try:
  409. wheel = Wheel(link.filename)
  410. except InvalidWheelFilename:
  411. logger.debug('Skipping %s because the wheel filename is invalid' % link)
  412. return []
  413. if wheel.name.lower() != search_name.lower():
  414. logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name))
  415. return []
  416. if not wheel.supported():
  417. logger.debug('Skipping %s because it is not compatible with this Python' % link)
  418. return []
  419. # This is a dirty hack to prevent installing Binary Wheels from
  420. # PyPI unless it is a Windows or Mac Binary Wheel. This is
  421. # paired with a change to PyPI disabling uploads for the
  422. # same. Once we have a mechanism for enabling support for binary
  423. # wheels on linux that deals with the inherent problems of
  424. # binary distribution this can be removed.
  425. comes_from = getattr(link, "comes_from", None)
  426. if ((
  427. not platform.startswith('win')
  428. and not platform.startswith('macosx')
  429. )
  430. and comes_from is not None
  431. and urlparse.urlparse(comes_from.url).netloc.endswith(
  432. "pypi.python.org")):
  433. if not wheel.supported(tags=supported_tags_noarch):
  434. logger.debug(
  435. "Skipping %s because it is a pypi-hosted binary "
  436. "Wheel on an unsupported platform" % link
  437. )
  438. return []
  439. version = wheel.version
  440. if not version:
  441. version = self._egg_info_matches(egg_info, search_name, link)
  442. if version is None:
  443. logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name))
  444. return []
  445. if (link.internal is not None
  446. and not link.internal
  447. and not normalize_name(search_name).lower() in self.allow_external
  448. and not self.allow_all_external):
  449. # We have a link that we are sure is external, so we should skip
  450. # it unless we are allowing externals
  451. logger.debug("Skipping %s because it is externally hosted." % link)
  452. self.need_warn_external = True
  453. return []
  454. if (link.verifiable is not None
  455. and not link.verifiable
  456. and not (normalize_name(search_name).lower()
  457. in self.allow_unverified)):
  458. # We have a link that we are sure we cannot verify it's integrity,
  459. # so we should skip it unless we are allowing unsafe installs
  460. # for this requirement.
  461. logger.debug("Skipping %s because it is an insecure and "
  462. "unverifiable file." % link)
  463. self.need_warn_unverified = True
  464. return []
  465. match = self._py_version_re.search(version)
  466. if match:
  467. version = version[:match.start()]
  468. py_version = match.group(1)
  469. if py_version != sys.version[:3]:
  470. logger.debug('Skipping %s because Python version is incorrect' % link)
  471. return []
  472. logger.debug('Found link %s, version: %s' % (link, version))
  473. return [(pkg_resources.parse_version(version),
  474. link,
  475. version)]
  476. def _egg_info_matches(self, egg_info, search_name, link):
  477. match = self._egg_info_re.search(egg_info)
  478. if not match:
  479. logger.debug('Could not parse version from link: %s' % link)
  480. return None
  481. name = match.group(0).lower()
  482. # To match the "safe" name that pkg_resources creates:
  483. name = name.replace('_', '-')
  484. # project name and version must be separated by a dash
  485. look_for = search_name.lower() + "-"
  486. if name.startswith(look_for):
  487. return match.group(0)[len(look_for):]
  488. else:
  489. return None
  490. def _get_page(self, link, req):
  491. return HTMLPage.get_page(link, req,
  492. cache=self.cache,
  493. session=self.session,
  494. )
  495. class PageCache(object):
  496. """Cache of HTML pages"""
  497. failure_limit = 3
  498. def __init__(self):
  499. self._failures = {}
  500. self._pages = {}
  501. self._archives = {}
  502. def too_many_failures(self, url):
  503. return self._failures.get(url, 0) >= self.failure_limit
  504. def get_page(self, url):
  505. return self._pages.get(url)
  506. def is_archive(self, url):
  507. return self._archives.get(url, False)
  508. def set_is_archive(self, url, value=True):
  509. self._archives[url] = value
  510. def add_page_failure(self, url, level):
  511. self._failures[url] = self._failures.get(url, 0)+level
  512. def add_page(self, urls, page):
  513. for url in urls:
  514. self._pages[url] = page
  515. class HTMLPage(object):
  516. """Represents one page, along with its URL"""
  517. ## FIXME: these regexes are horrible hacks:
  518. _homepage_re = re.compile(r'<th>\s*home\s*page', re.I)
  519. _download_re = re.compile(r'<th>\s*download\s+url', re.I)
  520. _href_re = re.compile('href=(?:"([^"]*)"|\'([^\']*)\'|([^>\\s\\n]*))', re.I|re.S)
  521. def __init__(self, content, url, headers=None, trusted=None):
  522. self.content = content
  523. self.parsed = html5lib.parse(self.content, namespaceHTMLElements=False)
  524. self.url = url
  525. self.headers = headers
  526. self.trusted = trusted
  527. def __str__(self):
  528. return self.url
  529. @classmethod
  530. def get_page(cls, link, req, cache=None, skip_archives=True, session=None):
  531. if session is None:
  532. session = PipSession()
  533. url = link.url
  534. url = url.split('#', 1)[0]
  535. if cache.too_many_failures(url):
  536. return None
  537. # Check for VCS schemes that do not support lookup as web pages.
  538. from pip.vcs import VcsSupport
  539. for scheme in VcsSupport.schemes:
  540. if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
  541. logger.debug('Cannot look at %(scheme)s URL %(link)s' % locals())
  542. return None
  543. if cache is not None:
  544. inst = cache.get_page(url)
  545. if inst is not None:
  546. return inst
  547. try:
  548. if skip_archives:
  549. if cache is not None:
  550. if cache.is_archive(url):
  551. return None
  552. filename = link.filename
  553. for bad_ext in ['.tar', '.tar.gz', '.tar.bz2', '.tgz', '.zip']:
  554. if filename.endswith(bad_ext):
  555. content_type = cls._get_content_type(url,
  556. session=session,
  557. )
  558. if content_type.lower().startswith('text/html'):
  559. break
  560. else:
  561. logger.debug('Skipping page %s because of Content-Type: %s' % (link, content_type))
  562. if cache is not None:
  563. cache.set_is_archive(url)
  564. return None
  565. logger.debug('Getting page %s' % url)
  566. # Tack index.html onto file:// URLs that point to directories
  567. (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
  568. if scheme == 'file' and os.path.isdir(url2pathname(path)):
  569. # add trailing slash if not present so urljoin doesn't trim final segment
  570. if not url.endswith('/'):
  571. url += '/'
  572. url = urlparse.urljoin(url, 'index.html')
  573. logger.debug(' file: URL is directory, getting %s' % url)
  574. resp = session.get(url, headers={"Accept": "text/html"})
  575. resp.raise_for_status()
  576. # The check for archives above only works if the url ends with
  577. # something that looks like an archive. However that is not a
  578. # requirement. For instance http://sourceforge.net/projects/docutils/files/docutils/0.8.1/docutils-0.8.1.tar.gz/download
  579. # redirects to http://superb-dca3.dl.sourceforge.net/project/docutils/docutils/0.8.1/docutils-0.8.1.tar.gz
  580. # Unless we issue a HEAD request on every url we cannot know
  581. # ahead of time for sure if something is HTML or not. However we
  582. # can check after we've downloaded it.
  583. content_type = resp.headers.get('Content-Type', 'unknown')
  584. if not content_type.lower().startswith("text/html"):
  585. logger.debug('Skipping page %s because of Content-Type: %s' %
  586. (link, content_type))
  587. if cache is not None:
  588. cache.set_is_archive(url)
  589. return None
  590. inst = cls(resp.text, resp.url, resp.headers, trusted=link.trusted)
  591. except requests.HTTPError as exc:
  592. level = 2 if exc.response.status_code == 404 else 1
  593. cls._handle_fail(req, link, exc, url, cache=cache, level=level)
  594. except requests.ConnectionError as exc:
  595. cls._handle_fail(
  596. req, link, "connection error: %s" % exc, url,
  597. cache=cache,
  598. )
  599. except requests.Timeout:
  600. cls._handle_fail(req, link, "timed out", url, cache=cache)
  601. except SSLError as exc:
  602. reason = ("There was a problem confirming the ssl certificate: "
  603. "%s" % exc)
  604. cls._handle_fail(req, link, reason, url,
  605. cache=cache,
  606. level=2,
  607. meth=logger.notify,
  608. )
  609. else:
  610. if cache is not None:
  611. cache.add_page([url, resp.url], inst)
  612. return inst
  613. @staticmethod
  614. def _handle_fail(req, link, reason, url, cache=None, level=1, meth=None):
  615. if meth is None:
  616. meth = logger.info
  617. meth("Could not fetch URL %s: %s", link, reason)
  618. meth("Will skip URL %s when looking for download links for %s" %
  619. (link.url, req))
  620. if cache is not None:
  621. cache.add_page_failure(url, level)
  622. @staticmethod
  623. def _get_content_type(url, session=None):
  624. """Get the Content-Type of the given url, using a HEAD request"""
  625. if session is None:
  626. session = PipSession()
  627. scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
  628. if not scheme in ('http', 'https', 'ftp', 'ftps'):
  629. ## FIXME: some warning or something?
  630. ## assertion error?
  631. return ''
  632. resp = session.head(url, allow_redirects=True)
  633. resp.raise_for_status()
  634. return resp.headers.get("Content-Type", "")
  635. @property
  636. def api_version(self):
  637. if not hasattr(self, "_api_version"):
  638. _api_version = None
  639. metas = [x for x in self.parsed.findall(".//meta")
  640. if x.get("name", "").lower() == "api-version"]
  641. if metas:
  642. try:
  643. _api_version = int(metas[0].get("value", None))
  644. except (TypeError, ValueError):
  645. _api_version = None
  646. self._api_version = _api_version
  647. return self._api_version
  648. @property
  649. def base_url(self):
  650. if not hasattr(self, "_base_url"):
  651. base = self.parsed.find(".//base")
  652. if base is not None and base.get("href"):
  653. self._base_url = base.get("href")
  654. else:
  655. self._base_url = self.url
  656. return self._base_url
  657. @property
  658. def links(self):
  659. """Yields all links in the page"""
  660. for anchor in self.parsed.findall(".//a"):
  661. if anchor.get("href"):
  662. href = anchor.get("href")
  663. url = self.clean_link(urlparse.urljoin(self.base_url, href))
  664. # Determine if this link is internal. If that distinction
  665. # doesn't make sense in this context, then we don't make
  666. # any distinction.
  667. internal = None
  668. if self.api_version and self.api_version >= 2:
  669. # Only api_versions >= 2 have a distinction between
  670. # external and internal links
  671. internal = bool(anchor.get("rel")
  672. and "internal" in anchor.get("rel").split())
  673. yield Link(url, self, internal=internal)
  674. def rel_links(self):
  675. for url in self.explicit_rel_links():
  676. yield url
  677. for url in self.scraped_rel_links():
  678. yield url
  679. def explicit_rel_links(self, rels=('homepage', 'download')):
  680. """Yields all links with the given relations"""
  681. rels = set(rels)
  682. for anchor in self.parsed.findall(".//a"):
  683. if anchor.get("rel") and anchor.get("href"):
  684. found_rels = set(anchor.get("rel").split())
  685. # Determine the intersection between what rels were found and
  686. # what rels were being looked for
  687. if found_rels & rels:
  688. href = anchor.get("href")
  689. url = self.clean_link(urlparse.urljoin(self.base_url, href))
  690. yield Link(url, self, trusted=False)
  691. def scraped_rel_links(self):
  692. # Can we get rid of this horrible horrible method?
  693. for regex in (self._homepage_re, self._download_re):
  694. match = regex.search(self.content)
  695. if not match:
  696. continue
  697. href_match = self._href_re.search(self.content, pos=match.end())
  698. if not href_match:
  699. continue
  700. url = href_match.group(1) or href_match.group(2) or href_match.group(3)
  701. if not url:
  702. continue
  703. url = self.clean_link(urlparse.urljoin(self.base_url, url))
  704. yield Link(url, self, trusted=False, _deprecated_regex=True)
  705. _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
  706. def clean_link(self, url):
  707. """Makes sure a link is fully encoded. That is, if a ' ' shows up in
  708. the link, it will be rewritten to %20 (while not over-quoting
  709. % or other characters)."""
  710. return self._clean_re.sub(
  711. lambda match: '%%%2x' % ord(match.group(0)), url)
  712. class Link(object):
  713. def __init__(self, url, comes_from=None, internal=None, trusted=None,
  714. _deprecated_regex=False):
  715. self.url = url
  716. self.comes_from = comes_from
  717. self.internal = internal
  718. self.trusted = trusted
  719. self._deprecated_regex = _deprecated_regex
  720. def __str__(self):
  721. if self.comes_from:
  722. return '%s (from %s)' % (self.url, self.comes_from)
  723. else:
  724. return str(self.url)
  725. def __repr__(self):
  726. return '<Link %s>' % self
  727. def __eq__(self, other):
  728. return self.url == other.url
  729. def __ne__(self, other):
  730. return self.url != other.url
  731. def __lt__(self, other):
  732. return self.url < other.url
  733. def __le__(self, other):
  734. return self.url <= other.url
  735. def __gt__(self, other):
  736. return self.url > other.url
  737. def __ge__(self, other):
  738. return self.url >= other.url
  739. def __hash__(self):
  740. return hash(self.url)
  741. @property
  742. def filename(self):
  743. _, netloc, path, _, _ = urlparse.urlsplit(self.url)
  744. name = posixpath.basename(path.rstrip('/')) or netloc
  745. assert name, ('URL %r produced no filename' % self.url)
  746. return name
  747. @property
  748. def scheme(self):
  749. return urlparse.urlsplit(self.url)[0]
  750. @property
  751. def path(self):
  752. return urlparse.urlsplit(self.url)[2]
  753. def splitext(self):
  754. return splitext(posixpath.basename(self.path.rstrip('/')))
  755. @property
  756. def ext(self):
  757. return self.splitext()[1]
  758. @property
  759. def url_without_fragment(self):
  760. scheme, netloc, path, query, fragment = urlparse.urlsplit(self.url)
  761. return urlparse.urlunsplit((scheme, netloc, path, query, None))
  762. _egg_fragment_re = re.compile(r'#egg=([^&]*)')
  763. @property
  764. def egg_fragment(self):
  765. match = self._egg_fragment_re.search(self.url)
  766. if not match:
  767. return None
  768. return match.group(1)
  769. _hash_re = re.compile(r'(sha1|sha224|sha384|sha256|sha512|md5)=([a-f0-9]+)')
  770. @property
  771. def hash(self):
  772. match = self._hash_re.search(self.url)
  773. if match:
  774. return match.group(2)
  775. return None
  776. @property
  777. def hash_name(self):
  778. match = self._hash_re.search(self.url)
  779. if match:
  780. return match.group(1)
  781. return None
  782. @property
  783. def show_url(self):
  784. return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0])
  785. @property
  786. def verifiable(self):
  787. """
  788. Returns True if this link can be verified after download, False if it
  789. cannot, and None if we cannot determine.
  790. """
  791. trusted = self.trusted or getattr(self.comes_from, "trusted", None)
  792. if trusted is not None and trusted:
  793. # This link came from a trusted source. It *may* be verifiable but
  794. # first we need to see if this page is operating under the new
  795. # API version.
  796. try:
  797. api_version = getattr(self.comes_from, "api_version", None)
  798. api_version = int(api_version)
  799. except (ValueError, TypeError):
  800. api_version = None
  801. if api_version is None or api_version <= 1:
  802. # This link is either trusted, or it came from a trusted,
  803. # however it is not operating under the API version 2 so
  804. # we can't make any claims about if it's safe or not
  805. return
  806. if self.hash:
  807. # This link came from a trusted source and it has a hash, so we
  808. # can consider it safe.
  809. return True
  810. else:
  811. # This link came from a trusted source, using the new API
  812. # version, and it does not have a hash. It is NOT verifiable
  813. return False
  814. elif trusted is not None:
  815. # This link came from an untrusted source and we cannot trust it
  816. return False
  817. # An object to represent the "link" for the installed version of a requirement.
  818. # Using Inf as the url makes it sort higher.
  819. INSTALLED_VERSION = Link(Inf)
  820. def get_requirement_from_url(url):
  821. """Get a requirement from the URL, if possible. This looks for #egg
  822. in the URL"""
  823. link = Link(url)
  824. egg_info = link.egg_fragment
  825. if not egg_info:
  826. egg_info = splitext(link.filename)[0]
  827. return package_to_requirement(egg_info)
  828. def package_to_requirement(package_name):
  829. """Translate a name like Foo-1.2 to Foo==1.3"""
  830. match = re.search(r'^(.*?)-(dev|\d.*)', package_name)
  831. if match:
  832. name = match.group(1)
  833. version = match.group(2)
  834. else:
  835. name = package_name
  836. version = ''
  837. if version:
  838. return '%s==%s' % (name, version)
  839. else:
  840. return name