package_index.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  1. """PyPI and direct package downloading"""
  2. import sys
  3. import subprocess
  4. import os
  5. import re
  6. import io
  7. import shutil
  8. import socket
  9. import base64
  10. import hashlib
  11. import itertools
  12. import warnings
  13. import configparser
  14. import html
  15. import http.client
  16. import urllib.parse
  17. import urllib.request
  18. import urllib.error
  19. from functools import wraps
  20. import setuptools
  21. from pkg_resources import (
  22. CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
  23. Environment, find_distributions, safe_name, safe_version,
  24. to_filename, Requirement, DEVELOP_DIST, EGG_DIST, parse_version,
  25. )
  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{0,10}=\s{0,10}['"]?([^'" >]+)[^>]*)>""", 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. self.opener = urllib.request.urlopen
  247. def add(self, dist):
  248. # ignore invalid versions
  249. try:
  250. parse_version(dist.version)
  251. except Exception:
  252. return
  253. return super().add(dist)
  254. # FIXME: 'PackageIndex.process_url' is too complex (14)
  255. def process_url(self, url, retrieve=False): # noqa: C901
  256. """Evaluate a URL as a possible download, and maybe retrieve it"""
  257. if url in self.scanned_urls and not retrieve:
  258. return
  259. self.scanned_urls[url] = True
  260. if not URL_SCHEME(url):
  261. self.process_filename(url)
  262. return
  263. else:
  264. dists = list(distros_for_url(url))
  265. if dists:
  266. if not self.url_ok(url):
  267. return
  268. self.debug("Found link: %s", url)
  269. if dists or not retrieve or url in self.fetched_urls:
  270. list(map(self.add, dists))
  271. return # don't need the actual page
  272. if not self.url_ok(url):
  273. self.fetched_urls[url] = True
  274. return
  275. self.info("Reading %s", url)
  276. self.fetched_urls[url] = True # prevent multiple fetch attempts
  277. tmpl = "Download error on %s: %%s -- Some packages may not be found!"
  278. f = self.open_url(url, tmpl % url)
  279. if f is None:
  280. return
  281. if isinstance(f, urllib.error.HTTPError) and f.code == 401:
  282. self.info("Authentication error: %s" % f.msg)
  283. self.fetched_urls[f.url] = True
  284. if 'html' not in f.headers.get('content-type', '').lower():
  285. f.close() # not html, we can't process it
  286. return
  287. base = f.url # handle redirects
  288. page = f.read()
  289. if not isinstance(page, str):
  290. # In Python 3 and got bytes but want str.
  291. if isinstance(f, urllib.error.HTTPError):
  292. # Errors have no charset, assume latin1:
  293. charset = 'latin-1'
  294. else:
  295. charset = f.headers.get_param('charset') or 'latin-1'
  296. page = page.decode(charset, "ignore")
  297. f.close()
  298. for match in HREF.finditer(page):
  299. link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
  300. self.process_url(link)
  301. if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
  302. page = self.process_index(url, page)
  303. def process_filename(self, fn, nested=False):
  304. # process filenames or directories
  305. if not os.path.exists(fn):
  306. self.warn("Not found: %s", fn)
  307. return
  308. if os.path.isdir(fn) and not nested:
  309. path = os.path.realpath(fn)
  310. for item in os.listdir(path):
  311. self.process_filename(os.path.join(path, item), True)
  312. dists = distros_for_filename(fn)
  313. if dists:
  314. self.debug("Found: %s", fn)
  315. list(map(self.add, dists))
  316. def url_ok(self, url, fatal=False):
  317. s = URL_SCHEME(url)
  318. is_file = s and s.group(1).lower() == 'file'
  319. if is_file or self.allows(urllib.parse.urlparse(url)[1]):
  320. return True
  321. msg = (
  322. "\nNote: Bypassing %s (disallowed host; see "
  323. "http://bit.ly/2hrImnY for details).\n")
  324. if fatal:
  325. raise DistutilsError(msg % url)
  326. else:
  327. self.warn(msg, url)
  328. def scan_egg_links(self, search_path):
  329. dirs = filter(os.path.isdir, search_path)
  330. egg_links = (
  331. (path, entry)
  332. for path in dirs
  333. for entry in os.listdir(path)
  334. if entry.endswith('.egg-link')
  335. )
  336. list(itertools.starmap(self.scan_egg_link, egg_links))
  337. def scan_egg_link(self, path, entry):
  338. with open(os.path.join(path, entry)) as raw_lines:
  339. # filter non-empty lines
  340. lines = list(filter(None, map(str.strip, raw_lines)))
  341. if len(lines) != 2:
  342. # format is not recognized; punt
  343. return
  344. egg_path, setup_path = lines
  345. for dist in find_distributions(os.path.join(path, egg_path)):
  346. dist.location = os.path.join(path, *lines)
  347. dist.precedence = SOURCE_DIST
  348. self.add(dist)
  349. def _scan(self, link):
  350. # Process a URL to see if it's for a package page
  351. NO_MATCH_SENTINEL = None, None
  352. if not link.startswith(self.index_url):
  353. return NO_MATCH_SENTINEL
  354. parts = list(map(
  355. urllib.parse.unquote, link[len(self.index_url):].split('/')
  356. ))
  357. if len(parts) != 2 or '#' in parts[1]:
  358. return NO_MATCH_SENTINEL
  359. # it's a package page, sanitize and index it
  360. pkg = safe_name(parts[0])
  361. ver = safe_version(parts[1])
  362. self.package_pages.setdefault(pkg.lower(), {})[link] = True
  363. return to_filename(pkg), to_filename(ver)
  364. def process_index(self, url, page):
  365. """Process the contents of a PyPI page"""
  366. # process an index page into the package-page index
  367. for match in HREF.finditer(page):
  368. try:
  369. self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
  370. except ValueError:
  371. pass
  372. pkg, ver = self._scan(url) # ensure this page is in the page index
  373. if not pkg:
  374. return "" # no sense double-scanning non-package pages
  375. # process individual package page
  376. for new_url in find_external_links(url, page):
  377. # Process the found URL
  378. base, frag = egg_info_for_url(new_url)
  379. if base.endswith('.py') and not frag:
  380. if ver:
  381. new_url += '#egg=%s-%s' % (pkg, ver)
  382. else:
  383. self.need_version_info(url)
  384. self.scan_url(new_url)
  385. return PYPI_MD5.sub(
  386. lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
  387. )
  388. def need_version_info(self, url):
  389. self.scan_all(
  390. "Page at %s links to .py file(s) without version info; an index "
  391. "scan is required.", url
  392. )
  393. def scan_all(self, msg=None, *args):
  394. if self.index_url not in self.fetched_urls:
  395. if msg:
  396. self.warn(msg, *args)
  397. self.info(
  398. "Scanning index of all packages (this may take a while)"
  399. )
  400. self.scan_url(self.index_url)
  401. def find_packages(self, requirement):
  402. self.scan_url(self.index_url + requirement.unsafe_name + '/')
  403. if not self.package_pages.get(requirement.key):
  404. # Fall back to safe version of the name
  405. self.scan_url(self.index_url + requirement.project_name + '/')
  406. if not self.package_pages.get(requirement.key):
  407. # We couldn't find the target package, so search the index page too
  408. self.not_found_in_index(requirement)
  409. for url in list(self.package_pages.get(requirement.key, ())):
  410. # scan each page that might be related to the desired package
  411. self.scan_url(url)
  412. def obtain(self, requirement, installer=None):
  413. self.prescan()
  414. self.find_packages(requirement)
  415. for dist in self[requirement.key]:
  416. if dist in requirement:
  417. return dist
  418. self.debug("%s does not match %s", requirement, dist)
  419. return super(PackageIndex, self).obtain(requirement, installer)
  420. def check_hash(self, checker, filename, tfp):
  421. """
  422. checker is a ContentChecker
  423. """
  424. checker.report(
  425. self.debug,
  426. "Validating %%s checksum for %s" % filename)
  427. if not checker.is_valid():
  428. tfp.close()
  429. os.unlink(filename)
  430. raise DistutilsError(
  431. "%s validation failed for %s; "
  432. "possible download problem?"
  433. % (checker.hash.name, os.path.basename(filename))
  434. )
  435. def add_find_links(self, urls):
  436. """Add `urls` to the list that will be prescanned for searches"""
  437. for url in urls:
  438. if (
  439. self.to_scan is None # if we have already "gone online"
  440. or not URL_SCHEME(url) # or it's a local file/directory
  441. or url.startswith('file:')
  442. or list(distros_for_url(url)) # or a direct package link
  443. ):
  444. # then go ahead and process it now
  445. self.scan_url(url)
  446. else:
  447. # otherwise, defer retrieval till later
  448. self.to_scan.append(url)
  449. def prescan(self):
  450. """Scan urls scheduled for prescanning (e.g. --find-links)"""
  451. if self.to_scan:
  452. list(map(self.scan_url, self.to_scan))
  453. self.to_scan = None # from now on, go ahead and process immediately
  454. def not_found_in_index(self, requirement):
  455. if self[requirement.key]: # we've seen at least one distro
  456. meth, msg = self.info, "Couldn't retrieve index page for %r"
  457. else: # no distros seen for this name, might be misspelled
  458. meth, msg = (
  459. self.warn,
  460. "Couldn't find index page for %r (maybe misspelled?)")
  461. meth(msg, requirement.unsafe_name)
  462. self.scan_all()
  463. def download(self, spec, tmpdir):
  464. """Locate and/or download `spec` to `tmpdir`, returning a local path
  465. `spec` may be a ``Requirement`` object, or a string containing a URL,
  466. an existing local filename, or a project/version requirement spec
  467. (i.e. the string form of a ``Requirement`` object). If it is the URL
  468. of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
  469. that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
  470. automatically created alongside the downloaded file.
  471. If `spec` is a ``Requirement`` object or a string containing a
  472. project/version requirement spec, this method returns the location of
  473. a matching distribution (possibly after downloading it to `tmpdir`).
  474. If `spec` is a locally existing file or directory name, it is simply
  475. returned unchanged. If `spec` is a URL, it is downloaded to a subpath
  476. of `tmpdir`, and the local filename is returned. Various errors may be
  477. raised if a problem occurs during downloading.
  478. """
  479. if not isinstance(spec, Requirement):
  480. scheme = URL_SCHEME(spec)
  481. if scheme:
  482. # It's a url, download it to tmpdir
  483. found = self._download_url(spec, tmpdir)
  484. base, fragment = egg_info_for_url(spec)
  485. if base.endswith('.py'):
  486. found = self.gen_setup(found, fragment, tmpdir)
  487. return found
  488. elif os.path.exists(spec):
  489. # Existing file or directory, just return it
  490. return spec
  491. else:
  492. spec = parse_requirement_arg(spec)
  493. return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
  494. def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME
  495. self, requirement, tmpdir, force_scan=False, source=False,
  496. develop_ok=False, local_index=None):
  497. """Obtain a distribution suitable for fulfilling `requirement`
  498. `requirement` must be a ``pkg_resources.Requirement`` instance.
  499. If necessary, or if the `force_scan` flag is set, the requirement is
  500. searched for in the (online) package index as well as the locally
  501. installed packages. If a distribution matching `requirement` is found,
  502. the returned distribution's ``location`` is the value you would have
  503. gotten from calling the ``download()`` method with the matching
  504. distribution's URL or filename. If no matching distribution is found,
  505. ``None`` is returned.
  506. If the `source` flag is set, only source distributions and source
  507. checkout links will be considered. Unless the `develop_ok` flag is
  508. set, development and system eggs (i.e., those using the ``.egg-info``
  509. format) will be ignored.
  510. """
  511. # process a Requirement
  512. self.info("Searching for %s", requirement)
  513. skipped = {}
  514. dist = None
  515. def find(req, env=None):
  516. if env is None:
  517. env = self
  518. # Find a matching distribution; may be called more than once
  519. for dist in env[req.key]:
  520. if dist.precedence == DEVELOP_DIST and not develop_ok:
  521. if dist not in skipped:
  522. self.warn(
  523. "Skipping development or system egg: %s", dist,
  524. )
  525. skipped[dist] = 1
  526. continue
  527. test = (
  528. dist in req
  529. and (dist.precedence <= SOURCE_DIST or not source)
  530. )
  531. if test:
  532. loc = self.download(dist.location, tmpdir)
  533. dist.download_location = loc
  534. if os.path.exists(dist.download_location):
  535. return dist
  536. if force_scan:
  537. self.prescan()
  538. self.find_packages(requirement)
  539. dist = find(requirement)
  540. if not dist and local_index is not None:
  541. dist = find(requirement, local_index)
  542. if dist is None:
  543. if self.to_scan is not None:
  544. self.prescan()
  545. dist = find(requirement)
  546. if dist is None and not force_scan:
  547. self.find_packages(requirement)
  548. dist = find(requirement)
  549. if dist is None:
  550. self.warn(
  551. "No local packages or working download links found for %s%s",
  552. (source and "a source distribution of " or ""),
  553. requirement,
  554. )
  555. else:
  556. self.info("Best match: %s", dist)
  557. return dist.clone(location=dist.download_location)
  558. def fetch(self, requirement, tmpdir, force_scan=False, source=False):
  559. """Obtain a file suitable for fulfilling `requirement`
  560. DEPRECATED; use the ``fetch_distribution()`` method now instead. For
  561. backward compatibility, this routine is identical but returns the
  562. ``location`` of the downloaded distribution instead of a distribution
  563. object.
  564. """
  565. dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
  566. if dist is not None:
  567. return dist.location
  568. return None
  569. def gen_setup(self, filename, fragment, tmpdir):
  570. match = EGG_FRAGMENT.match(fragment)
  571. dists = match and [
  572. d for d in
  573. interpret_distro_name(filename, match.group(1), None) if d.version
  574. ] or []
  575. if len(dists) == 1: # unambiguous ``#egg`` fragment
  576. basename = os.path.basename(filename)
  577. # Make sure the file has been downloaded to the temp dir.
  578. if os.path.dirname(filename) != tmpdir:
  579. dst = os.path.join(tmpdir, basename)
  580. from setuptools.command.easy_install import samefile
  581. if not samefile(filename, dst):
  582. shutil.copy2(filename, dst)
  583. filename = dst
  584. with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
  585. file.write(
  586. "from setuptools import setup\n"
  587. "setup(name=%r, version=%r, py_modules=[%r])\n"
  588. % (
  589. dists[0].project_name, dists[0].version,
  590. os.path.splitext(basename)[0]
  591. )
  592. )
  593. return filename
  594. elif match:
  595. raise DistutilsError(
  596. "Can't unambiguously interpret project/version identifier %r; "
  597. "any dashes in the name or version should be escaped using "
  598. "underscores. %r" % (fragment, dists)
  599. )
  600. else:
  601. raise DistutilsError(
  602. "Can't process plain .py files without an '#egg=name-version'"
  603. " suffix to enable automatic setup script generation."
  604. )
  605. dl_blocksize = 8192
  606. def _download_to(self, url, filename):
  607. self.info("Downloading %s", url)
  608. # Download the file
  609. fp = None
  610. try:
  611. checker = HashChecker.from_url(url)
  612. fp = self.open_url(url)
  613. if isinstance(fp, urllib.error.HTTPError):
  614. raise DistutilsError(
  615. "Can't download %s: %s %s" % (url, fp.code, fp.msg)
  616. )
  617. headers = fp.info()
  618. blocknum = 0
  619. bs = self.dl_blocksize
  620. size = -1
  621. if "content-length" in headers:
  622. # Some servers return multiple Content-Length headers :(
  623. sizes = headers.get_all('Content-Length')
  624. size = max(map(int, sizes))
  625. self.reporthook(url, filename, blocknum, bs, size)
  626. with open(filename, 'wb') as tfp:
  627. while True:
  628. block = fp.read(bs)
  629. if block:
  630. checker.feed(block)
  631. tfp.write(block)
  632. blocknum += 1
  633. self.reporthook(url, filename, blocknum, bs, size)
  634. else:
  635. break
  636. self.check_hash(checker, filename, tfp)
  637. return headers
  638. finally:
  639. if fp:
  640. fp.close()
  641. def reporthook(self, url, filename, blocknum, blksize, size):
  642. pass # no-op
  643. # FIXME:
  644. def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
  645. if url.startswith('file:'):
  646. return local_open(url)
  647. try:
  648. return open_with_auth(url, self.opener)
  649. except (ValueError, http.client.InvalidURL) as v:
  650. msg = ' '.join([str(arg) for arg in v.args])
  651. if warning:
  652. self.warn(warning, msg)
  653. else:
  654. raise DistutilsError('%s %s' % (url, msg)) from v
  655. except urllib.error.HTTPError as v:
  656. return v
  657. except urllib.error.URLError as v:
  658. if warning:
  659. self.warn(warning, v.reason)
  660. else:
  661. raise DistutilsError("Download error for %s: %s"
  662. % (url, v.reason)) from v
  663. except http.client.BadStatusLine as v:
  664. if warning:
  665. self.warn(warning, v.line)
  666. else:
  667. raise DistutilsError(
  668. '%s returned a bad status line. The server might be '
  669. 'down, %s' %
  670. (url, v.line)
  671. ) from v
  672. except (http.client.HTTPException, socket.error) as v:
  673. if warning:
  674. self.warn(warning, v)
  675. else:
  676. raise DistutilsError("Download error for %s: %s"
  677. % (url, v)) from v
  678. @staticmethod
  679. def _resolve_download_filename(url, tmpdir):
  680. """
  681. >>> import pathlib
  682. >>> du = PackageIndex._resolve_download_filename
  683. >>> root = getfixture('tmp_path')
  684. >>> url = 'https://files.pythonhosted.org/packages/a9/5a/0db.../setuptools-78.1.0.tar.gz'
  685. >>> str(pathlib.Path(du(url, root)).relative_to(root))
  686. 'setuptools-78.1.0.tar.gz'
  687. Ensures the target is always in tmpdir.
  688. >>> url = 'https://anyhost/%2fhome%2fuser%2f.ssh%2fauthorized_keys'
  689. >>> du(url, root)
  690. Traceback (most recent call last):
  691. ...
  692. ValueError: Invalid filename...
  693. """
  694. name, fragment = egg_info_for_url(url)
  695. if name:
  696. while '..' in name:
  697. name = name.replace('..', '.').replace('\\', '_')
  698. else:
  699. name = "__downloaded__" # default if URL has no path contents
  700. if name.endswith('.egg.zip'):
  701. name = name[:-4] # strip the extra .zip before download
  702. filename = os.path.join(tmpdir, name)
  703. # ensure path resolves within the tmpdir
  704. if not filename.startswith(str(tmpdir)):
  705. raise ValueError(f"Invalid filename {filename}")
  706. return filename
  707. def _download_url(self, url, tmpdir):
  708. """
  709. Determine the download filename.
  710. """
  711. filename = self._resolve_download_filename(url, tmpdir)
  712. return self._download_vcs(url, filename) or self._download_other(url, filename)
  713. @staticmethod
  714. def _resolve_vcs(url):
  715. """
  716. >>> rvcs = PackageIndex._resolve_vcs
  717. >>> rvcs('git+http://foo/bar')
  718. 'git'
  719. >>> rvcs('hg+https://foo/bar')
  720. 'hg'
  721. >>> rvcs('git:myhost')
  722. 'git'
  723. >>> rvcs('hg:myhost')
  724. >>> rvcs('http://foo/bar')
  725. """
  726. scheme = urllib.parse.urlsplit(url).scheme
  727. pre, sep, post = scheme.partition('+')
  728. # svn and git have their own protocol; hg does not
  729. allowed = set(['svn', 'git'] + ['hg'] * bool(sep))
  730. return next(iter({pre} & allowed), None)
  731. def _download_vcs(self, url, spec_filename):
  732. vcs = self._resolve_vcs(url)
  733. if not vcs:
  734. return
  735. if vcs == 'svn':
  736. return self._download_svn(url, spec_filename)
  737. filename, _, _ = spec_filename.partition('#')
  738. url, rev = self._vcs_split_rev_from_url(url)
  739. self.info(f"Doing {vcs} clone from {url} to {filename}")
  740. subprocess.check_call([vcs, 'clone', '--quiet', url, filename])
  741. co_commands = dict(
  742. git=[vcs, '-C', filename, 'checkout', '--quiet', rev],
  743. hg=[vcs, '--cwd', filename, 'up', '-C', '-r', rev, '-q'],
  744. )
  745. if rev is not None:
  746. self.info(f"Checking out {rev}")
  747. subprocess.check_call(co_commands[vcs])
  748. return filename
  749. def _download_other(self, url, filename):
  750. scheme = urllib.parse.urlsplit(url).scheme
  751. if scheme == 'file': # pragma: no cover
  752. return urllib.request.url2pathname(urllib.parse.urlparse(url).path)
  753. # raise error if not allowed
  754. self.url_ok(url, True)
  755. return self._attempt_download(url, filename)
  756. def scan_url(self, url):
  757. self.process_url(url, True)
  758. def _attempt_download(self, url, filename):
  759. headers = self._download_to(url, filename)
  760. if 'html' in headers.get('content-type', '').lower():
  761. return self._download_html(url, headers, filename)
  762. else:
  763. return filename
  764. def _download_html(self, url, headers, filename):
  765. file = open(filename)
  766. for line in file:
  767. if line.strip():
  768. # Check for a subversion index page
  769. if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
  770. # it's a subversion index page:
  771. file.close()
  772. os.unlink(filename)
  773. return self._download_svn(url, filename)
  774. break # not an index page
  775. file.close()
  776. os.unlink(filename)
  777. raise DistutilsError("Unexpected HTML page found at " + url)
  778. def _download_svn(self, url, filename):
  779. warnings.warn("SVN download support is deprecated", UserWarning)
  780. url = url.split('#', 1)[0] # remove any fragment for svn's sake
  781. creds = []
  782. if url.lower().startswith('svn:') and '@' in url:
  783. scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
  784. if not netloc and path.startswith('//') and '/' in path[2:]:
  785. netloc, path = path[2:].split('/', 1)
  786. auth, host = _splituser(netloc)
  787. if auth:
  788. if ':' in auth:
  789. user, pw = auth.split(':', 1)
  790. creds.extend(["--username", user, "--password", pw])
  791. else:
  792. creds.extend(["--username", auth])
  793. netloc = host
  794. parts = scheme, netloc, url, p, q, f
  795. url = urllib.parse.urlunparse(parts)
  796. self.info("Doing subversion checkout from %s to %s", url, filename)
  797. cmd = ["svn", "checkout", "-q"] + creds + [url, filename]
  798. subprocess.check_call(cmd)
  799. return filename
  800. @staticmethod
  801. def _vcs_split_rev_from_url(url):
  802. """
  803. Given a possible VCS URL, return a clean URL and resolved revision if any.
  804. >>> vsrfu = PackageIndex._vcs_split_rev_from_url
  805. >>> vsrfu('git+https://github.com/pypa/setuptools@v69.0.0#egg-info=setuptools')
  806. ('https://github.com/pypa/setuptools', 'v69.0.0')
  807. >>> vsrfu('git+https://github.com/pypa/setuptools#egg-info=setuptools')
  808. ('https://github.com/pypa/setuptools', None)
  809. >>> vsrfu('http://foo/bar')
  810. ('http://foo/bar', None)
  811. """
  812. parts = urllib.parse.urlsplit(url)
  813. clean_scheme = parts.scheme.split('+', 1)[-1]
  814. # Some fragment identification fails
  815. no_fragment_path, _, _ = parts.path.partition('#')
  816. pre, sep, post = no_fragment_path.rpartition('@')
  817. clean_path, rev = (pre, post) if sep else (post, None)
  818. resolved = parts._replace(
  819. scheme=clean_scheme,
  820. path=clean_path,
  821. # discard the fragment
  822. fragment='',
  823. ).geturl()
  824. return resolved, rev
  825. def debug(self, msg, *args):
  826. log.debug(msg, *args)
  827. def info(self, msg, *args):
  828. log.info(msg, *args)
  829. def warn(self, msg, *args):
  830. log.warn(msg, *args)
  831. # This pattern matches a character entity reference (a decimal numeric
  832. # references, a hexadecimal numeric reference, or a named reference).
  833. entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
  834. def decode_entity(match):
  835. what = match.group(0)
  836. return html.unescape(what)
  837. def htmldecode(text):
  838. """
  839. Decode HTML entities in the given text.
  840. >>> htmldecode(
  841. ... 'https://../package_name-0.1.2.tar.gz'
  842. ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
  843. 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
  844. """
  845. return entity_sub(decode_entity, text)
  846. def socket_timeout(timeout=15):
  847. def _socket_timeout(func):
  848. def _socket_timeout(*args, **kwargs):
  849. old_timeout = socket.getdefaulttimeout()
  850. socket.setdefaulttimeout(timeout)
  851. try:
  852. return func(*args, **kwargs)
  853. finally:
  854. socket.setdefaulttimeout(old_timeout)
  855. return _socket_timeout
  856. return _socket_timeout
  857. def _encode_auth(auth):
  858. """
  859. Encode auth from a URL suitable for an HTTP header.
  860. >>> str(_encode_auth('username%3Apassword'))
  861. 'dXNlcm5hbWU6cGFzc3dvcmQ='
  862. Long auth strings should not cause a newline to be inserted.
  863. >>> long_auth = 'username:' + 'password'*10
  864. >>> chr(10) in str(_encode_auth(long_auth))
  865. False
  866. """
  867. auth_s = urllib.parse.unquote(auth)
  868. # convert to bytes
  869. auth_bytes = auth_s.encode()
  870. encoded_bytes = base64.b64encode(auth_bytes)
  871. # convert back to a string
  872. encoded = encoded_bytes.decode()
  873. # strip the trailing carriage return
  874. return encoded.replace('\n', '')
  875. class Credential:
  876. """
  877. A username/password pair. Use like a namedtuple.
  878. """
  879. def __init__(self, username, password):
  880. self.username = username
  881. self.password = password
  882. def __iter__(self):
  883. yield self.username
  884. yield self.password
  885. def __str__(self):
  886. return '%(username)s:%(password)s' % vars(self)
  887. class PyPIConfig(configparser.RawConfigParser):
  888. def __init__(self):
  889. """
  890. Load from ~/.pypirc
  891. """
  892. defaults = dict.fromkeys(['username', 'password', 'repository'], '')
  893. configparser.RawConfigParser.__init__(self, defaults)
  894. rc = os.path.join(os.path.expanduser('~'), '.pypirc')
  895. if os.path.exists(rc):
  896. self.read(rc)
  897. @property
  898. def creds_by_repository(self):
  899. sections_with_repositories = [
  900. section for section in self.sections()
  901. if self.get(section, 'repository').strip()
  902. ]
  903. return dict(map(self._get_repo_cred, sections_with_repositories))
  904. def _get_repo_cred(self, section):
  905. repo = self.get(section, 'repository').strip()
  906. return repo, Credential(
  907. self.get(section, 'username').strip(),
  908. self.get(section, 'password').strip(),
  909. )
  910. def find_credential(self, url):
  911. """
  912. If the URL indicated appears to be a repository defined in this
  913. config, return the credential for that repository.
  914. """
  915. for repository, cred in self.creds_by_repository.items():
  916. if url.startswith(repository):
  917. return cred
  918. def open_with_auth(url, opener=urllib.request.urlopen):
  919. """Open a urllib2 request, handling HTTP authentication"""
  920. parsed = urllib.parse.urlparse(url)
  921. scheme, netloc, path, params, query, frag = parsed
  922. # Double scheme does not raise on macOS as revealed by a
  923. # failing test. We would expect "nonnumeric port". Refs #20.
  924. if netloc.endswith(':'):
  925. raise http.client.InvalidURL("nonnumeric port: ''")
  926. if scheme in ('http', 'https'):
  927. auth, address = _splituser(netloc)
  928. else:
  929. auth = None
  930. if not auth:
  931. cred = PyPIConfig().find_credential(url)
  932. if cred:
  933. auth = str(cred)
  934. info = cred.username, url
  935. log.info('Authenticating as %s for %s (from .pypirc)', *info)
  936. if auth:
  937. auth = "Basic " + _encode_auth(auth)
  938. parts = scheme, address, path, params, query, frag
  939. new_url = urllib.parse.urlunparse(parts)
  940. request = urllib.request.Request(new_url)
  941. request.add_header("Authorization", auth)
  942. else:
  943. request = urllib.request.Request(url)
  944. request.add_header('User-Agent', user_agent)
  945. fp = opener(request)
  946. if auth:
  947. # Put authentication info back into request URL if same host,
  948. # so that links found on the page will work
  949. s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
  950. if s2 == scheme and h2 == address:
  951. parts = s2, netloc, path2, param2, query2, frag2
  952. fp.url = urllib.parse.urlunparse(parts)
  953. return fp
  954. # copy of urllib.parse._splituser from Python 3.8
  955. def _splituser(host):
  956. """splituser('user[:passwd]@host[:port]')
  957. --> 'user[:passwd]', 'host[:port]'."""
  958. user, delim, host = host.rpartition('@')
  959. return (user if delim else None), host
  960. # adding a timeout to avoid freezing package_index
  961. open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
  962. def fix_sf_url(url):
  963. return url # backward compatibility
  964. def local_open(url):
  965. """Read a local path, with special support for directories"""
  966. scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
  967. filename = urllib.request.url2pathname(path)
  968. if os.path.isfile(filename):
  969. return urllib.request.urlopen(url)
  970. elif path.endswith('/') and os.path.isdir(filename):
  971. files = []
  972. for f in os.listdir(filename):
  973. filepath = os.path.join(filename, f)
  974. if f == 'index.html':
  975. with open(filepath, 'r') as fp:
  976. body = fp.read()
  977. break
  978. elif os.path.isdir(filepath):
  979. f += '/'
  980. files.append('<a href="{name}">{name}</a>'.format(name=f))
  981. else:
  982. tmpl = (
  983. "<html><head><title>{url}</title>"
  984. "</head><body>{files}</body></html>")
  985. body = tmpl.format(url=url, files='\n'.join(files))
  986. status, message = 200, "OK"
  987. else:
  988. status, message, body = 404, "Path not found", "Not found"
  989. headers = {'content-type': 'text/html'}
  990. body_stream = io.StringIO(body)
  991. return urllib.error.HTTPError(url, status, message, headers, body_stream)