You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1129 lines
39KB

  1. """PyPI and direct package downloading"""
  2. import sys
  3. import os
  4. import re
  5. import io
  6. import shutil
  7. import socket
  8. import base64
  9. import hashlib
  10. import itertools
  11. import warnings
  12. import configparser
  13. import html
  14. import http.client
  15. import urllib.parse
  16. import urllib.request
  17. import urllib.error
  18. from functools import wraps
  19. import setuptools
  20. from pkg_resources import (
  21. CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
  22. Environment, find_distributions, safe_name, safe_version,
  23. to_filename, Requirement, DEVELOP_DIST, EGG_DIST,
  24. )
  25. from setuptools import ssl_support
  26. from distutils import log
  27. from distutils.errors import DistutilsError
  28. from fnmatch import translate
  29. from setuptools.wheel import Wheel
  30. from setuptools.extern.more_itertools import unique_everseen
  31. EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
  32. HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
  33. PYPI_MD5 = re.compile(
  34. r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
  35. r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
  36. )
  37. URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
  38. EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
  39. __all__ = [
  40. 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
  41. 'interpret_distro_name',
  42. ]
  43. _SOCKET_TIMEOUT = 15
  44. _tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
  45. user_agent = _tmpl.format(
  46. py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
  47. def parse_requirement_arg(spec):
  48. try:
  49. return Requirement.parse(spec)
  50. except ValueError as e:
  51. raise DistutilsError(
  52. "Not a URL, existing file, or requirement spec: %r" % (spec,)
  53. ) from e
  54. def parse_bdist_wininst(name):
  55. """Return (base,pyversion) or (None,None) for possible .exe name"""
  56. lower = name.lower()
  57. base, py_ver, plat = None, None, None
  58. if lower.endswith('.exe'):
  59. if lower.endswith('.win32.exe'):
  60. base = name[:-10]
  61. plat = 'win32'
  62. elif lower.startswith('.win32-py', -16):
  63. py_ver = name[-7:-4]
  64. base = name[:-16]
  65. plat = 'win32'
  66. elif lower.endswith('.win-amd64.exe'):
  67. base = name[:-14]
  68. plat = 'win-amd64'
  69. elif lower.startswith('.win-amd64-py', -20):
  70. py_ver = name[-7:-4]
  71. base = name[:-20]
  72. plat = 'win-amd64'
  73. return base, py_ver, plat
  74. def egg_info_for_url(url):
  75. parts = urllib.parse.urlparse(url)
  76. scheme, server, path, parameters, query, fragment = parts
  77. base = urllib.parse.unquote(path.split('/')[-1])
  78. if server == 'sourceforge.net' and base == 'download': # XXX Yuck
  79. base = urllib.parse.unquote(path.split('/')[-2])
  80. if '#' in base:
  81. base, fragment = base.split('#', 1)
  82. return base, fragment
  83. def distros_for_url(url, metadata=None):
  84. """Yield egg or source distribution objects that might be found at a URL"""
  85. base, fragment = egg_info_for_url(url)
  86. for dist in distros_for_location(url, base, metadata):
  87. yield dist
  88. if fragment:
  89. match = EGG_FRAGMENT.match(fragment)
  90. if match:
  91. for dist in interpret_distro_name(
  92. url, match.group(1), metadata, precedence=CHECKOUT_DIST
  93. ):
  94. yield dist
  95. def distros_for_location(location, basename, metadata=None):
  96. """Yield egg or source distribution objects based on basename"""
  97. if basename.endswith('.egg.zip'):
  98. basename = basename[:-4] # strip the .zip
  99. if basename.endswith('.egg') and '-' in basename:
  100. # only one, unambiguous interpretation
  101. return [Distribution.from_location(location, basename, metadata)]
  102. if basename.endswith('.whl') and '-' in basename:
  103. wheel = Wheel(basename)
  104. if not wheel.is_compatible():
  105. return []
  106. return [Distribution(
  107. location=location,
  108. project_name=wheel.project_name,
  109. version=wheel.version,
  110. # Increase priority over eggs.
  111. precedence=EGG_DIST + 1,
  112. )]
  113. if basename.endswith('.exe'):
  114. win_base, py_ver, platform = parse_bdist_wininst(basename)
  115. if win_base is not None:
  116. return interpret_distro_name(
  117. location, win_base, metadata, py_ver, BINARY_DIST, platform
  118. )
  119. # Try source distro extensions (.zip, .tgz, etc.)
  120. #
  121. for ext in EXTENSIONS:
  122. if basename.endswith(ext):
  123. basename = basename[:-len(ext)]
  124. return interpret_distro_name(location, basename, metadata)
  125. return [] # no extension matched
  126. def distros_for_filename(filename, metadata=None):
  127. """Yield possible egg or source distribution objects based on a filename"""
  128. return distros_for_location(
  129. normalize_path(filename), os.path.basename(filename), metadata
  130. )
  131. def interpret_distro_name(
  132. location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
  133. platform=None
  134. ):
  135. """Generate alternative interpretations of a source distro name
  136. Note: if `location` is a filesystem filename, you should call
  137. ``pkg_resources.normalize_path()`` on it before passing it to this
  138. routine!
  139. """
  140. # Generate alternative interpretations of a source distro name
  141. # Because some packages are ambiguous as to name/versions split
  142. # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
  143. # So, we generate each possible interpretation (e.g. "adns, python-1.1.0"
  144. # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
  145. # the spurious interpretations should be ignored, because in the event
  146. # there's also an "adns" package, the spurious "python-1.1.0" version will
  147. # compare lower than any numeric version number, and is therefore unlikely
  148. # to match a request for it. It's still a potential problem, though, and
  149. # in the long run PyPI and the distutils should go for "safe" names and
  150. # versions in distribution archive names (sdist and bdist).
  151. parts = basename.split('-')
  152. if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
  153. # it is a bdist_dumb, not an sdist -- bail out
  154. return
  155. for p in range(1, len(parts) + 1):
  156. yield Distribution(
  157. location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
  158. py_version=py_version, precedence=precedence,
  159. platform=platform
  160. )
  161. def unique_values(func):
  162. """
  163. Wrap a function returning an iterable such that the resulting iterable
  164. only ever yields unique items.
  165. """
  166. @wraps(func)
  167. def wrapper(*args, **kwargs):
  168. return unique_everseen(func(*args, **kwargs))
  169. return wrapper
  170. REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
  171. # this line is here to fix emacs' cruddy broken syntax highlighting
  172. @unique_values
  173. def find_external_links(url, page):
  174. """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
  175. for match in REL.finditer(page):
  176. tag, rel = match.groups()
  177. rels = set(map(str.strip, rel.lower().split(',')))
  178. if 'homepage' in rels or 'download' in rels:
  179. for match in HREF.finditer(tag):
  180. yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
  181. for tag in ("<th>Home Page", "<th>Download URL"):
  182. pos = page.find(tag)
  183. if pos != -1:
  184. match = HREF.search(page, pos)
  185. if match:
  186. yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
  187. class ContentChecker:
  188. """
  189. A null content checker that defines the interface for checking content
  190. """
  191. def feed(self, block):
  192. """
  193. Feed a block of data to the hash.
  194. """
  195. return
  196. def is_valid(self):
  197. """
  198. Check the hash. Return False if validation fails.
  199. """
  200. return True
  201. def report(self, reporter, template):
  202. """
  203. Call reporter with information about the checker (hash name)
  204. substituted into the template.
  205. """
  206. return
  207. class HashChecker(ContentChecker):
  208. pattern = re.compile(
  209. r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
  210. r'(?P<expected>[a-f0-9]+)'
  211. )
  212. def __init__(self, hash_name, expected):
  213. self.hash_name = hash_name
  214. self.hash = hashlib.new(hash_name)
  215. self.expected = expected
  216. @classmethod
  217. def from_url(cls, url):
  218. "Construct a (possibly null) ContentChecker from a URL"
  219. fragment = urllib.parse.urlparse(url)[-1]
  220. if not fragment:
  221. return ContentChecker()
  222. match = cls.pattern.search(fragment)
  223. if not match:
  224. return ContentChecker()
  225. return cls(**match.groupdict())
  226. def feed(self, block):
  227. self.hash.update(block)
  228. def is_valid(self):
  229. return self.hash.hexdigest() == self.expected
  230. def report(self, reporter, template):
  231. msg = template % self.hash_name
  232. return reporter(msg)
  233. class PackageIndex(Environment):
  234. """A distribution index that scans web pages for download URLs"""
  235. def __init__(
  236. self, index_url="https://pypi.org/simple/", hosts=('*',),
  237. ca_bundle=None, verify_ssl=True, *args, **kw
  238. ):
  239. Environment.__init__(self, *args, **kw)
  240. self.index_url = index_url + "/" [:not index_url.endswith('/')]
  241. self.scanned_urls = {}
  242. self.fetched_urls = {}
  243. self.package_pages = {}
  244. self.allows = re.compile('|'.join(map(translate, hosts))).match
  245. self.to_scan = []
  246. use_ssl = (
  247. verify_ssl
  248. and ssl_support.is_available
  249. and (ca_bundle or ssl_support.find_ca_bundle())
  250. )
  251. if use_ssl:
  252. self.opener = ssl_support.opener_for(ca_bundle)
  253. else:
  254. self.opener = urllib.request.urlopen
  255. # FIXME: 'PackageIndex.process_url' is too complex (14)
  256. def process_url(self, url, retrieve=False): # noqa: C901
  257. """Evaluate a URL as a possible download, and maybe retrieve it"""
  258. if url in self.scanned_urls and not retrieve:
  259. return
  260. self.scanned_urls[url] = True
  261. if not URL_SCHEME(url):
  262. self.process_filename(url)
  263. return
  264. else:
  265. dists = list(distros_for_url(url))
  266. if dists:
  267. if not self.url_ok(url):
  268. return
  269. self.debug("Found link: %s", url)
  270. if dists or not retrieve or url in self.fetched_urls:
  271. list(map(self.add, dists))
  272. return # don't need the actual page
  273. if not self.url_ok(url):
  274. self.fetched_urls[url] = True
  275. return
  276. self.info("Reading %s", url)
  277. self.fetched_urls[url] = True # prevent multiple fetch attempts
  278. tmpl = "Download error on %s: %%s -- Some packages may not be found!"
  279. f = self.open_url(url, tmpl % url)
  280. if f is None:
  281. return
  282. if isinstance(f, urllib.error.HTTPError) and f.code == 401:
  283. self.info("Authentication error: %s" % f.msg)
  284. self.fetched_urls[f.url] = True
  285. if 'html' not in f.headers.get('content-type', '').lower():
  286. f.close() # not html, we can't process it
  287. return
  288. base = f.url # handle redirects
  289. page = f.read()
  290. if not isinstance(page, str):
  291. # In Python 3 and got bytes but want str.
  292. if isinstance(f, urllib.error.HTTPError):
  293. # Errors have no charset, assume latin1:
  294. charset = 'latin-1'
  295. else:
  296. charset = f.headers.get_param('charset') or 'latin-1'
  297. page = page.decode(charset, "ignore")
  298. f.close()
  299. for match in HREF.finditer(page):
  300. link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
  301. self.process_url(link)
  302. if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
  303. page = self.process_index(url, page)
  304. def process_filename(self, fn, nested=False):
  305. # process filenames or directories
  306. if not os.path.exists(fn):
  307. self.warn("Not found: %s", fn)
  308. return
  309. if os.path.isdir(fn) and not nested:
  310. path = os.path.realpath(fn)
  311. for item in os.listdir(path):
  312. self.process_filename(os.path.join(path, item), True)
  313. dists = distros_for_filename(fn)
  314. if dists:
  315. self.debug("Found: %s", fn)
  316. list(map(self.add, dists))
  317. def url_ok(self, url, fatal=False):
  318. s = URL_SCHEME(url)
  319. is_file = s and s.group(1).lower() == 'file'
  320. if is_file or self.allows(urllib.parse.urlparse(url)[1]):
  321. return True
  322. msg = (
  323. "\nNote: Bypassing %s (disallowed host; see "
  324. "http://bit.ly/2hrImnY for details).\n")
  325. if fatal:
  326. raise DistutilsError(msg % url)
  327. else:
  328. self.warn(msg, url)
  329. def scan_egg_links(self, search_path):
  330. dirs = filter(os.path.isdir, search_path)
  331. egg_links = (
  332. (path, entry)
  333. for path in dirs
  334. for entry in os.listdir(path)
  335. if entry.endswith('.egg-link')
  336. )
  337. list(itertools.starmap(self.scan_egg_link, egg_links))
  338. def scan_egg_link(self, path, entry):
  339. with open(os.path.join(path, entry)) as raw_lines:
  340. # filter non-empty lines
  341. lines = list(filter(None, map(str.strip, raw_lines)))
  342. if len(lines) != 2:
  343. # format is not recognized; punt
  344. return
  345. egg_path, setup_path = lines
  346. for dist in find_distributions(os.path.join(path, egg_path)):
  347. dist.location = os.path.join(path, *lines)
  348. dist.precedence = SOURCE_DIST
  349. self.add(dist)
  350. def _scan(self, link):
  351. # Process a URL to see if it's for a package page
  352. NO_MATCH_SENTINEL = None, None
  353. if not link.startswith(self.index_url):
  354. return NO_MATCH_SENTINEL
  355. parts = list(map(
  356. urllib.parse.unquote, link[len(self.index_url):].split('/')
  357. ))
  358. if len(parts) != 2 or '#' in parts[1]:
  359. return NO_MATCH_SENTINEL
  360. # it's a package page, sanitize and index it
  361. pkg = safe_name(parts[0])
  362. ver = safe_version(parts[1])
  363. self.package_pages.setdefault(pkg.lower(), {})[link] = True
  364. return to_filename(pkg), to_filename(ver)
  365. def process_index(self, url, page):
  366. """Process the contents of a PyPI page"""
  367. # process an index page into the package-page index
  368. for match in HREF.finditer(page):
  369. try:
  370. self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
  371. except ValueError:
  372. pass
  373. pkg, ver = self._scan(url) # ensure this page is in the page index
  374. if not pkg:
  375. return "" # no sense double-scanning non-package pages
  376. # process individual package page
  377. for new_url in find_external_links(url, page):
  378. # Process the found URL
  379. base, frag = egg_info_for_url(new_url)
  380. if base.endswith('.py') and not frag:
  381. if ver:
  382. new_url += '#egg=%s-%s' % (pkg, ver)
  383. else:
  384. self.need_version_info(url)
  385. self.scan_url(new_url)
  386. return PYPI_MD5.sub(
  387. lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
  388. )
  389. def need_version_info(self, url):
  390. self.scan_all(
  391. "Page at %s links to .py file(s) without version info; an index "
  392. "scan is required.", url
  393. )
  394. def scan_all(self, msg=None, *args):
  395. if self.index_url not in self.fetched_urls:
  396. if msg:
  397. self.warn(msg, *args)
  398. self.info(
  399. "Scanning index of all packages (this may take a while)"
  400. )
  401. self.scan_url(self.index_url)
  402. def find_packages(self, requirement):
  403. self.scan_url(self.index_url + requirement.unsafe_name + '/')
  404. if not self.package_pages.get(requirement.key):
  405. # Fall back to safe version of the name
  406. self.scan_url(self.index_url + requirement.project_name + '/')
  407. if not self.package_pages.get(requirement.key):
  408. # We couldn't find the target package, so search the index page too
  409. self.not_found_in_index(requirement)
  410. for url in list(self.package_pages.get(requirement.key, ())):
  411. # scan each page that might be related to the desired package
  412. self.scan_url(url)
  413. def obtain(self, requirement, installer=None):
  414. self.prescan()
  415. self.find_packages(requirement)
  416. for dist in self[requirement.key]:
  417. if dist in requirement:
  418. return dist
  419. self.debug("%s does not match %s", requirement, dist)
  420. return super(PackageIndex, self).obtain(requirement, installer)
  421. def check_hash(self, checker, filename, tfp):
  422. """
  423. checker is a ContentChecker
  424. """
  425. checker.report(
  426. self.debug,
  427. "Validating %%s checksum for %s" % filename)
  428. if not checker.is_valid():
  429. tfp.close()
  430. os.unlink(filename)
  431. raise DistutilsError(
  432. "%s validation failed for %s; "
  433. "possible download problem?"
  434. % (checker.hash.name, os.path.basename(filename))
  435. )
  436. def add_find_links(self, urls):
  437. """Add `urls` to the list that will be prescanned for searches"""
  438. for url in urls:
  439. if (
  440. self.to_scan is None # if we have already "gone online"
  441. or not URL_SCHEME(url) # or it's a local file/directory
  442. or url.startswith('file:')
  443. or list(distros_for_url(url)) # or a direct package link
  444. ):
  445. # then go ahead and process it now
  446. self.scan_url(url)
  447. else:
  448. # otherwise, defer retrieval till later
  449. self.to_scan.append(url)
  450. def prescan(self):
  451. """Scan urls scheduled for prescanning (e.g. --find-links)"""
  452. if self.to_scan:
  453. list(map(self.scan_url, self.to_scan))
  454. self.to_scan = None # from now on, go ahead and process immediately
  455. def not_found_in_index(self, requirement):
  456. if self[requirement.key]: # we've seen at least one distro
  457. meth, msg = self.info, "Couldn't retrieve index page for %r"
  458. else: # no distros seen for this name, might be misspelled
  459. meth, msg = (
  460. self.warn,
  461. "Couldn't find index page for %r (maybe misspelled?)")
  462. meth(msg, requirement.unsafe_name)
  463. self.scan_all()
  464. def download(self, spec, tmpdir):
  465. """Locate and/or download `spec` to `tmpdir`, returning a local path
  466. `spec` may be a ``Requirement`` object, or a string containing a URL,
  467. an existing local filename, or a project/version requirement spec
  468. (i.e. the string form of a ``Requirement`` object). If it is the URL
  469. of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
  470. that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
  471. automatically created alongside the downloaded file.
  472. If `spec` is a ``Requirement`` object or a string containing a
  473. project/version requirement spec, this method returns the location of
  474. a matching distribution (possibly after downloading it to `tmpdir`).
  475. If `spec` is a locally existing file or directory name, it is simply
  476. returned unchanged. If `spec` is a URL, it is downloaded to a subpath
  477. of `tmpdir`, and the local filename is returned. Various errors may be
  478. raised if a problem occurs during downloading.
  479. """
  480. if not isinstance(spec, Requirement):
  481. scheme = URL_SCHEME(spec)
  482. if scheme:
  483. # It's a url, download it to tmpdir
  484. found = self._download_url(scheme.group(1), spec, tmpdir)
  485. base, fragment = egg_info_for_url(spec)
  486. if base.endswith('.py'):
  487. found = self.gen_setup(found, fragment, tmpdir)
  488. return found
  489. elif os.path.exists(spec):
  490. # Existing file or directory, just return it
  491. return spec
  492. else:
  493. spec = parse_requirement_arg(spec)
  494. return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
  495. def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME
  496. self, requirement, tmpdir, force_scan=False, source=False,
  497. develop_ok=False, local_index=None):
  498. """Obtain a distribution suitable for fulfilling `requirement`
  499. `requirement` must be a ``pkg_resources.Requirement`` instance.
  500. If necessary, or if the `force_scan` flag is set, the requirement is
  501. searched for in the (online) package index as well as the locally
  502. installed packages. If a distribution matching `requirement` is found,
  503. the returned distribution's ``location`` is the value you would have
  504. gotten from calling the ``download()`` method with the matching
  505. distribution's URL or filename. If no matching distribution is found,
  506. ``None`` is returned.
  507. If the `source` flag is set, only source distributions and source
  508. checkout links will be considered. Unless the `develop_ok` flag is
  509. set, development and system eggs (i.e., those using the ``.egg-info``
  510. format) will be ignored.
  511. """
  512. # process a Requirement
  513. self.info("Searching for %s", requirement)
  514. skipped = {}
  515. dist = None
  516. def find(req, env=None):
  517. if env is None:
  518. env = self
  519. # Find a matching distribution; may be called more than once
  520. for dist in env[req.key]:
  521. if dist.precedence == DEVELOP_DIST and not develop_ok:
  522. if dist not in skipped:
  523. self.warn(
  524. "Skipping development or system egg: %s", dist,
  525. )
  526. skipped[dist] = 1
  527. continue
  528. test = (
  529. dist in req
  530. and (dist.precedence <= SOURCE_DIST or not source)
  531. )
  532. if test:
  533. loc = self.download(dist.location, tmpdir)
  534. dist.download_location = loc
  535. if os.path.exists(dist.download_location):
  536. return dist
  537. if force_scan:
  538. self.prescan()
  539. self.find_packages(requirement)
  540. dist = find(requirement)
  541. if not dist and local_index is not None:
  542. dist = find(requirement, local_index)
  543. if dist is None:
  544. if self.to_scan is not None:
  545. self.prescan()
  546. dist = find(requirement)
  547. if dist is None and not force_scan:
  548. self.find_packages(requirement)
  549. dist = find(requirement)
  550. if dist is None:
  551. self.warn(
  552. "No local packages or working download links found for %s%s",
  553. (source and "a source distribution of " or ""),
  554. requirement,
  555. )
  556. else:
  557. self.info("Best match: %s", dist)
  558. return dist.clone(location=dist.download_location)
  559. def fetch(self, requirement, tmpdir, force_scan=False, source=False):
  560. """Obtain a file suitable for fulfilling `requirement`
  561. DEPRECATED; use the ``fetch_distribution()`` method now instead. For
  562. backward compatibility, this routine is identical but returns the
  563. ``location`` of the downloaded distribution instead of a distribution
  564. object.
  565. """
  566. dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
  567. if dist is not None:
  568. return dist.location
  569. return None
  570. def gen_setup(self, filename, fragment, tmpdir):
  571. match = EGG_FRAGMENT.match(fragment)
  572. dists = match and [
  573. d for d in
  574. interpret_distro_name(filename, match.group(1), None) if d.version
  575. ] or []
  576. if len(dists) == 1: # unambiguous ``#egg`` fragment
  577. basename = os.path.basename(filename)
  578. # Make sure the file has been downloaded to the temp dir.
  579. if os.path.dirname(filename) != tmpdir:
  580. dst = os.path.join(tmpdir, basename)
  581. from setuptools.command.easy_install import samefile
  582. if not samefile(filename, dst):
  583. shutil.copy2(filename, dst)
  584. filename = dst
  585. with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
  586. file.write(
  587. "from setuptools import setup\n"
  588. "setup(name=%r, version=%r, py_modules=[%r])\n"
  589. % (
  590. dists[0].project_name, dists[0].version,
  591. os.path.splitext(basename)[0]
  592. )
  593. )
  594. return filename
  595. elif match:
  596. raise DistutilsError(
  597. "Can't unambiguously interpret project/version identifier %r; "
  598. "any dashes in the name or version should be escaped using "
  599. "underscores. %r" % (fragment, dists)
  600. )
  601. else:
  602. raise DistutilsError(
  603. "Can't process plain .py files without an '#egg=name-version'"
  604. " suffix to enable automatic setup script generation."
  605. )
  606. dl_blocksize = 8192
  607. def _download_to(self, url, filename):
  608. self.info("Downloading %s", url)
  609. # Download the file
  610. fp = None
  611. try:
  612. checker = HashChecker.from_url(url)
  613. fp = self.open_url(url)
  614. if isinstance(fp, urllib.error.HTTPError):
  615. raise DistutilsError(
  616. "Can't download %s: %s %s" % (url, fp.code, fp.msg)
  617. )
  618. headers = fp.info()
  619. blocknum = 0
  620. bs = self.dl_blocksize
  621. size = -1
  622. if "content-length" in headers:
  623. # Some servers return multiple Content-Length headers :(
  624. sizes = headers.get_all('Content-Length')
  625. size = max(map(int, sizes))
  626. self.reporthook(url, filename, blocknum, bs, size)
  627. with open(filename, 'wb') as tfp:
  628. while True:
  629. block = fp.read(bs)
  630. if block:
  631. checker.feed(block)
  632. tfp.write(block)
  633. blocknum += 1
  634. self.reporthook(url, filename, blocknum, bs, size)
  635. else:
  636. break
  637. self.check_hash(checker, filename, tfp)
  638. return headers
  639. finally:
  640. if fp:
  641. fp.close()
  642. def reporthook(self, url, filename, blocknum, blksize, size):
  643. pass # no-op
  644. # FIXME:
  645. def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
  646. if url.startswith('file:'):
  647. return local_open(url)
  648. try:
  649. return open_with_auth(url, self.opener)
  650. except (ValueError, http.client.InvalidURL) as v:
  651. msg = ' '.join([str(arg) for arg in v.args])
  652. if warning:
  653. self.warn(warning, msg)
  654. else:
  655. raise DistutilsError('%s %s' % (url, msg)) from v
  656. except urllib.error.HTTPError as v:
  657. return v
  658. except urllib.error.URLError as v:
  659. if warning:
  660. self.warn(warning, v.reason)
  661. else:
  662. raise DistutilsError("Download error for %s: %s"
  663. % (url, v.reason)) from v
  664. except http.client.BadStatusLine as v:
  665. if warning:
  666. self.warn(warning, v.line)
  667. else:
  668. raise DistutilsError(
  669. '%s returned a bad status line. The server might be '
  670. 'down, %s' %
  671. (url, v.line)
  672. ) from v
  673. except (http.client.HTTPException, socket.error) as v:
  674. if warning:
  675. self.warn(warning, v)
  676. else:
  677. raise DistutilsError("Download error for %s: %s"
  678. % (url, v)) from v
  679. def _download_url(self, scheme, url, tmpdir):
  680. # Determine download filename
  681. #
  682. name, fragment = egg_info_for_url(url)
  683. if name:
  684. while '..' in name:
  685. name = name.replace('..', '.').replace('\\', '_')
  686. else:
  687. name = "__downloaded__" # default if URL has no path contents
  688. if name.endswith('.egg.zip'):
  689. name = name[:-4] # strip the extra .zip before download
  690. filename = os.path.join(tmpdir, name)
  691. # Download the file
  692. #
  693. if scheme == 'svn' or scheme.startswith('svn+'):
  694. return self._download_svn(url, filename)
  695. elif scheme == 'git' or scheme.startswith('git+'):
  696. return self._download_git(url, filename)
  697. elif scheme.startswith('hg+'):
  698. return self._download_hg(url, filename)
  699. elif scheme == 'file':
  700. return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
  701. else:
  702. self.url_ok(url, True) # raises error if not allowed
  703. return self._attempt_download(url, filename)
  704. def scan_url(self, url):
  705. self.process_url(url, True)
  706. def _attempt_download(self, url, filename):
  707. headers = self._download_to(url, filename)
  708. if 'html' in headers.get('content-type', '').lower():
  709. return self._download_html(url, headers, filename)
  710. else:
  711. return filename
  712. def _download_html(self, url, headers, filename):
  713. file = open(filename)
  714. for line in file:
  715. if line.strip():
  716. # Check for a subversion index page
  717. if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
  718. # it's a subversion index page:
  719. file.close()
  720. os.unlink(filename)
  721. return self._download_svn(url, filename)
  722. break # not an index page
  723. file.close()
  724. os.unlink(filename)
  725. raise DistutilsError("Unexpected HTML page found at " + url)
  726. def _download_svn(self, url, filename):
  727. warnings.warn("SVN download support is deprecated", UserWarning)
  728. url = url.split('#', 1)[0] # remove any fragment for svn's sake
  729. creds = ''
  730. if url.lower().startswith('svn:') and '@' in url:
  731. scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
  732. if not netloc and path.startswith('//') and '/' in path[2:]:
  733. netloc, path = path[2:].split('/', 1)
  734. auth, host = _splituser(netloc)
  735. if auth:
  736. if ':' in auth:
  737. user, pw = auth.split(':', 1)
  738. creds = " --username=%s --password=%s" % (user, pw)
  739. else:
  740. creds = " --username=" + auth
  741. netloc = host
  742. parts = scheme, netloc, url, p, q, f
  743. url = urllib.parse.urlunparse(parts)
  744. self.info("Doing subversion checkout from %s to %s", url, filename)
  745. os.system("svn checkout%s -q %s %s" % (creds, url, filename))
  746. return filename
  747. @staticmethod
  748. def _vcs_split_rev_from_url(url, pop_prefix=False):
  749. scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
  750. scheme = scheme.split('+', 1)[-1]
  751. # Some fragment identification fails
  752. path = path.split('#', 1)[0]
  753. rev = None
  754. if '@' in path:
  755. path, rev = path.rsplit('@', 1)
  756. # Also, discard fragment
  757. url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
  758. return url, rev
  759. def _download_git(self, url, filename):
  760. filename = filename.split('#', 1)[0]
  761. url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
  762. self.info("Doing git clone from %s to %s", url, filename)
  763. os.system("git clone --quiet %s %s" % (url, filename))
  764. if rev is not None:
  765. self.info("Checking out %s", rev)
  766. os.system("git -C %s checkout --quiet %s" % (
  767. filename,
  768. rev,
  769. ))
  770. return filename
  771. def _download_hg(self, url, filename):
  772. filename = filename.split('#', 1)[0]
  773. url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
  774. self.info("Doing hg clone from %s to %s", url, filename)
  775. os.system("hg clone --quiet %s %s" % (url, filename))
  776. if rev is not None:
  777. self.info("Updating to %s", rev)
  778. os.system("hg --cwd %s up -C -r %s -q" % (
  779. filename,
  780. rev,
  781. ))
  782. return filename
  783. def debug(self, msg, *args):
  784. log.debug(msg, *args)
  785. def info(self, msg, *args):
  786. log.info(msg, *args)
  787. def warn(self, msg, *args):
  788. log.warn(msg, *args)
  789. # This pattern matches a character entity reference (a decimal numeric
  790. # references, a hexadecimal numeric reference, or a named reference).
  791. entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
  792. def decode_entity(match):
  793. what = match.group(0)
  794. return html.unescape(what)
  795. def htmldecode(text):
  796. """
  797. Decode HTML entities in the given text.
  798. >>> htmldecode(
  799. ... 'https://../package_name-0.1.2.tar.gz'
  800. ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
  801. 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
  802. """
  803. return entity_sub(decode_entity, text)
  804. def socket_timeout(timeout=15):
  805. def _socket_timeout(func):
  806. def _socket_timeout(*args, **kwargs):
  807. old_timeout = socket.getdefaulttimeout()
  808. socket.setdefaulttimeout(timeout)
  809. try:
  810. return func(*args, **kwargs)
  811. finally:
  812. socket.setdefaulttimeout(old_timeout)
  813. return _socket_timeout
  814. return _socket_timeout
  815. def _encode_auth(auth):
  816. """
  817. Encode auth from a URL suitable for an HTTP header.
  818. >>> str(_encode_auth('username%3Apassword'))
  819. 'dXNlcm5hbWU6cGFzc3dvcmQ='
  820. Long auth strings should not cause a newline to be inserted.
  821. >>> long_auth = 'username:' + 'password'*10
  822. >>> chr(10) in str(_encode_auth(long_auth))
  823. False
  824. """
  825. auth_s = urllib.parse.unquote(auth)
  826. # convert to bytes
  827. auth_bytes = auth_s.encode()
  828. encoded_bytes = base64.b64encode(auth_bytes)
  829. # convert back to a string
  830. encoded = encoded_bytes.decode()
  831. # strip the trailing carriage return
  832. return encoded.replace('\n', '')
  833. class Credential:
  834. """
  835. A username/password pair. Use like a namedtuple.
  836. """
  837. def __init__(self, username, password):
  838. self.username = username
  839. self.password = password
  840. def __iter__(self):
  841. yield self.username
  842. yield self.password
  843. def __str__(self):
  844. return '%(username)s:%(password)s' % vars(self)
  845. class PyPIConfig(configparser.RawConfigParser):
  846. def __init__(self):
  847. """
  848. Load from ~/.pypirc
  849. """
  850. defaults = dict.fromkeys(['username', 'password', 'repository'], '')
  851. configparser.RawConfigParser.__init__(self, defaults)
  852. rc = os.path.join(os.path.expanduser('~'), '.pypirc')
  853. if os.path.exists(rc):
  854. self.read(rc)
  855. @property
  856. def creds_by_repository(self):
  857. sections_with_repositories = [
  858. section for section in self.sections()
  859. if self.get(section, 'repository').strip()
  860. ]
  861. return dict(map(self._get_repo_cred, sections_with_repositories))
  862. def _get_repo_cred(self, section):
  863. repo = self.get(section, 'repository').strip()
  864. return repo, Credential(
  865. self.get(section, 'username').strip(),
  866. self.get(section, 'password').strip(),
  867. )
  868. def find_credential(self, url):
  869. """
  870. If the URL indicated appears to be a repository defined in this
  871. config, return the credential for that repository.
  872. """
  873. for repository, cred in self.creds_by_repository.items():
  874. if url.startswith(repository):
  875. return cred
  876. def open_with_auth(url, opener=urllib.request.urlopen):
  877. """Open a urllib2 request, handling HTTP authentication"""
  878. parsed = urllib.parse.urlparse(url)
  879. scheme, netloc, path, params, query, frag = parsed
  880. # Double scheme does not raise on macOS as revealed by a
  881. # failing test. We would expect "nonnumeric port". Refs #20.
  882. if netloc.endswith(':'):
  883. raise http.client.InvalidURL("nonnumeric port: ''")
  884. if scheme in ('http', 'https'):
  885. auth, address = _splituser(netloc)
  886. else:
  887. auth = None
  888. if not auth:
  889. cred = PyPIConfig().find_credential(url)
  890. if cred:
  891. auth = str(cred)
  892. info = cred.username, url
  893. log.info('Authenticating as %s for %s (from .pypirc)', *info)
  894. if auth:
  895. auth = "Basic " + _encode_auth(auth)
  896. parts = scheme, address, path, params, query, frag
  897. new_url = urllib.parse.urlunparse(parts)
  898. request = urllib.request.Request(new_url)
  899. request.add_header("Authorization", auth)
  900. else:
  901. request = urllib.request.Request(url)
  902. request.add_header('User-Agent', user_agent)
  903. fp = opener(request)
  904. if auth:
  905. # Put authentication info back into request URL if same host,
  906. # so that links found on the page will work
  907. s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
  908. if s2 == scheme and h2 == address:
  909. parts = s2, netloc, path2, param2, query2, frag2
  910. fp.url = urllib.parse.urlunparse(parts)
  911. return fp
  912. # copy of urllib.parse._splituser from Python 3.8
  913. def _splituser(host):
  914. """splituser('user[:passwd]@host[:port]')
  915. --> 'user[:passwd]', 'host[:port]'."""
  916. user, delim, host = host.rpartition('@')
  917. return (user if delim else None), host
  918. # adding a timeout to avoid freezing package_index
  919. open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
  920. def fix_sf_url(url):
  921. return url # backward compatibility
  922. def local_open(url):
  923. """Read a local path, with special support for directories"""
  924. scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
  925. filename = urllib.request.url2pathname(path)
  926. if os.path.isfile(filename):
  927. return urllib.request.urlopen(url)
  928. elif path.endswith('/') and os.path.isdir(filename):
  929. files = []
  930. for f in os.listdir(filename):
  931. filepath = os.path.join(filename, f)
  932. if f == 'index.html':
  933. with open(filepath, 'r') as fp:
  934. body = fp.read()
  935. break
  936. elif os.path.isdir(filepath):
  937. f += '/'
  938. files.append('<a href="{name}">{name}</a>'.format(name=f))
  939. else:
  940. tmpl = (
  941. "<html><head><title>{url}</title>"
  942. "</head><body>{files}</body></html>")
  943. body = tmpl.format(url=url, files='\n'.join(files))
  944. status, message = 200, "OK"
  945. else:
  946. status, message, body = 404, "Path not found", "Not found"
  947. headers = {'content-type': 'text/html'}
  948. body_stream = io.StringIO(body)
  949. return urllib.error.HTTPError(url, status, message, headers, body_stream)