package_index.py 39 KB

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