PageRenderTime 70ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/pip/index.py

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