package_index.py 37 KB

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