Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

490 řádky
14 KiB

  1. import os
  2. import sys
  3. import tempfile
  4. import operator
  5. import functools
  6. import itertools
  7. import re
  8. import contextlib
  9. import pickle
  10. import pkg_resources
  11. if sys.platform.startswith('java'):
  12. import org.python.modules.posix.PosixModule as _os
  13. else:
  14. _os = sys.modules[os.name]
  15. try:
  16. _file = file
  17. except NameError:
  18. _file = None
  19. _open = open
  20. from distutils.errors import DistutilsError
  21. from pkg_resources import working_set
  22. from setuptools import compat
  23. from setuptools.compat import builtins
  24. __all__ = [
  25. "AbstractSandbox", "DirectorySandbox", "SandboxViolation", "run_setup",
  26. ]
  27. def _execfile(filename, globals, locals=None):
  28. """
  29. Python 3 implementation of execfile.
  30. """
  31. mode = 'rb'
  32. with open(filename, mode) as stream:
  33. script = stream.read()
  34. # compile() function in Python 2.6 and 3.1 requires LF line endings.
  35. if sys.version_info[:2] < (2, 7) or sys.version_info[:2] >= (3, 0) and sys.version_info[:2] < (3, 2):
  36. script = script.replace(b'\r\n', b'\n')
  37. script = script.replace(b'\r', b'\n')
  38. if locals is None:
  39. locals = globals
  40. code = compile(script, filename, 'exec')
  41. exec(code, globals, locals)
  42. @contextlib.contextmanager
  43. def save_argv(repl=None):
  44. saved = sys.argv[:]
  45. if repl is not None:
  46. sys.argv[:] = repl
  47. try:
  48. yield saved
  49. finally:
  50. sys.argv[:] = saved
  51. @contextlib.contextmanager
  52. def save_path():
  53. saved = sys.path[:]
  54. try:
  55. yield saved
  56. finally:
  57. sys.path[:] = saved
  58. @contextlib.contextmanager
  59. def override_temp(replacement):
  60. """
  61. Monkey-patch tempfile.tempdir with replacement, ensuring it exists
  62. """
  63. if not os.path.isdir(replacement):
  64. os.makedirs(replacement)
  65. saved = tempfile.tempdir
  66. tempfile.tempdir = replacement
  67. try:
  68. yield
  69. finally:
  70. tempfile.tempdir = saved
  71. @contextlib.contextmanager
  72. def pushd(target):
  73. saved = os.getcwd()
  74. os.chdir(target)
  75. try:
  76. yield saved
  77. finally:
  78. os.chdir(saved)
  79. class UnpickleableException(Exception):
  80. """
  81. An exception representing another Exception that could not be pickled.
  82. """
  83. @classmethod
  84. def dump(cls, type, exc):
  85. """
  86. Always return a dumped (pickled) type and exc. If exc can't be pickled,
  87. wrap it in UnpickleableException first.
  88. """
  89. try:
  90. return pickle.dumps(type), pickle.dumps(exc)
  91. except Exception:
  92. return cls.dump(cls, cls(repr(exc)))
  93. class ExceptionSaver:
  94. """
  95. A Context Manager that will save an exception, serialized, and restore it
  96. later.
  97. """
  98. def __enter__(self):
  99. return self
  100. def __exit__(self, type, exc, tb):
  101. if not exc:
  102. return
  103. # dump the exception
  104. self._saved = UnpickleableException.dump(type, exc)
  105. self._tb = tb
  106. # suppress the exception
  107. return True
  108. def resume(self):
  109. "restore and re-raise any exception"
  110. if '_saved' not in vars(self):
  111. return
  112. type, exc = map(pickle.loads, self._saved)
  113. compat.reraise(type, exc, self._tb)
  114. @contextlib.contextmanager
  115. def save_modules():
  116. """
  117. Context in which imported modules are saved.
  118. Translates exceptions internal to the context into the equivalent exception
  119. outside the context.
  120. """
  121. saved = sys.modules.copy()
  122. with ExceptionSaver() as saved_exc:
  123. yield saved
  124. sys.modules.update(saved)
  125. # remove any modules imported since
  126. del_modules = (
  127. mod_name for mod_name in sys.modules
  128. if mod_name not in saved
  129. # exclude any encodings modules. See #285
  130. and not mod_name.startswith('encodings.')
  131. )
  132. _clear_modules(del_modules)
  133. saved_exc.resume()
  134. def _clear_modules(module_names):
  135. for mod_name in list(module_names):
  136. del sys.modules[mod_name]
  137. @contextlib.contextmanager
  138. def save_pkg_resources_state():
  139. saved = pkg_resources.__getstate__()
  140. try:
  141. yield saved
  142. finally:
  143. pkg_resources.__setstate__(saved)
  144. @contextlib.contextmanager
  145. def setup_context(setup_dir):
  146. temp_dir = os.path.join(setup_dir, 'temp')
  147. with save_pkg_resources_state():
  148. with save_modules():
  149. hide_setuptools()
  150. with save_path():
  151. with save_argv():
  152. with override_temp(temp_dir):
  153. with pushd(setup_dir):
  154. # ensure setuptools commands are available
  155. __import__('setuptools')
  156. yield
  157. def _needs_hiding(mod_name):
  158. """
  159. >>> _needs_hiding('setuptools')
  160. True
  161. >>> _needs_hiding('pkg_resources')
  162. True
  163. >>> _needs_hiding('setuptools_plugin')
  164. False
  165. >>> _needs_hiding('setuptools.__init__')
  166. True
  167. >>> _needs_hiding('distutils')
  168. True
  169. """
  170. pattern = re.compile('(setuptools|pkg_resources|distutils)(\.|$)')
  171. return bool(pattern.match(mod_name))
  172. def hide_setuptools():
  173. """
  174. Remove references to setuptools' modules from sys.modules to allow the
  175. invocation to import the most appropriate setuptools. This technique is
  176. necessary to avoid issues such as #315 where setuptools upgrading itself
  177. would fail to find a function declared in the metadata.
  178. """
  179. modules = filter(_needs_hiding, sys.modules)
  180. _clear_modules(modules)
  181. def run_setup(setup_script, args):
  182. """Run a distutils setup script, sandboxed in its directory"""
  183. setup_dir = os.path.abspath(os.path.dirname(setup_script))
  184. with setup_context(setup_dir):
  185. try:
  186. sys.argv[:] = [setup_script]+list(args)
  187. sys.path.insert(0, setup_dir)
  188. # reset to include setup dir, w/clean callback list
  189. working_set.__init__()
  190. working_set.callbacks.append(lambda dist:dist.activate())
  191. def runner():
  192. ns = dict(__file__=setup_script, __name__='__main__')
  193. _execfile(setup_script, ns)
  194. DirectorySandbox(setup_dir).run(runner)
  195. except SystemExit as v:
  196. if v.args and v.args[0]:
  197. raise
  198. # Normal exit, just return
  199. class AbstractSandbox:
  200. """Wrap 'os' module and 'open()' builtin for virtualizing setup scripts"""
  201. _active = False
  202. def __init__(self):
  203. self._attrs = [
  204. name for name in dir(_os)
  205. if not name.startswith('_') and hasattr(self,name)
  206. ]
  207. def _copy(self, source):
  208. for name in self._attrs:
  209. setattr(os, name, getattr(source,name))
  210. def run(self, func):
  211. """Run 'func' under os sandboxing"""
  212. try:
  213. self._copy(self)
  214. if _file:
  215. builtins.file = self._file
  216. builtins.open = self._open
  217. self._active = True
  218. return func()
  219. finally:
  220. self._active = False
  221. if _file:
  222. builtins.file = _file
  223. builtins.open = _open
  224. self._copy(_os)
  225. def _mk_dual_path_wrapper(name):
  226. original = getattr(_os,name)
  227. def wrap(self,src,dst,*args,**kw):
  228. if self._active:
  229. src,dst = self._remap_pair(name,src,dst,*args,**kw)
  230. return original(src,dst,*args,**kw)
  231. return wrap
  232. for name in ["rename", "link", "symlink"]:
  233. if hasattr(_os,name): locals()[name] = _mk_dual_path_wrapper(name)
  234. def _mk_single_path_wrapper(name, original=None):
  235. original = original or getattr(_os,name)
  236. def wrap(self,path,*args,**kw):
  237. if self._active:
  238. path = self._remap_input(name,path,*args,**kw)
  239. return original(path,*args,**kw)
  240. return wrap
  241. if _file:
  242. _file = _mk_single_path_wrapper('file', _file)
  243. _open = _mk_single_path_wrapper('open', _open)
  244. for name in [
  245. "stat", "listdir", "chdir", "open", "chmod", "chown", "mkdir",
  246. "remove", "unlink", "rmdir", "utime", "lchown", "chroot", "lstat",
  247. "startfile", "mkfifo", "mknod", "pathconf", "access"
  248. ]:
  249. if hasattr(_os,name): locals()[name] = _mk_single_path_wrapper(name)
  250. def _mk_single_with_return(name):
  251. original = getattr(_os,name)
  252. def wrap(self,path,*args,**kw):
  253. if self._active:
  254. path = self._remap_input(name,path,*args,**kw)
  255. return self._remap_output(name, original(path,*args,**kw))
  256. return original(path,*args,**kw)
  257. return wrap
  258. for name in ['readlink', 'tempnam']:
  259. if hasattr(_os,name): locals()[name] = _mk_single_with_return(name)
  260. def _mk_query(name):
  261. original = getattr(_os,name)
  262. def wrap(self,*args,**kw):
  263. retval = original(*args,**kw)
  264. if self._active:
  265. return self._remap_output(name, retval)
  266. return retval
  267. return wrap
  268. for name in ['getcwd', 'tmpnam']:
  269. if hasattr(_os,name): locals()[name] = _mk_query(name)
  270. def _validate_path(self,path):
  271. """Called to remap or validate any path, whether input or output"""
  272. return path
  273. def _remap_input(self,operation,path,*args,**kw):
  274. """Called for path inputs"""
  275. return self._validate_path(path)
  276. def _remap_output(self,operation,path):
  277. """Called for path outputs"""
  278. return self._validate_path(path)
  279. def _remap_pair(self,operation,src,dst,*args,**kw):
  280. """Called for path pairs like rename, link, and symlink operations"""
  281. return (
  282. self._remap_input(operation+'-from',src,*args,**kw),
  283. self._remap_input(operation+'-to',dst,*args,**kw)
  284. )
  285. if hasattr(os, 'devnull'):
  286. _EXCEPTIONS = [os.devnull,]
  287. else:
  288. _EXCEPTIONS = []
  289. try:
  290. from win32com.client.gencache import GetGeneratePath
  291. _EXCEPTIONS.append(GetGeneratePath())
  292. del GetGeneratePath
  293. except ImportError:
  294. # it appears pywin32 is not installed, so no need to exclude.
  295. pass
  296. class DirectorySandbox(AbstractSandbox):
  297. """Restrict operations to a single subdirectory - pseudo-chroot"""
  298. write_ops = dict.fromkeys([
  299. "open", "chmod", "chown", "mkdir", "remove", "unlink", "rmdir",
  300. "utime", "lchown", "chroot", "mkfifo", "mknod", "tempnam",
  301. ])
  302. _exception_patterns = [
  303. # Allow lib2to3 to attempt to save a pickled grammar object (#121)
  304. '.*lib2to3.*\.pickle$',
  305. ]
  306. "exempt writing to paths that match the pattern"
  307. def __init__(self, sandbox, exceptions=_EXCEPTIONS):
  308. self._sandbox = os.path.normcase(os.path.realpath(sandbox))
  309. self._prefix = os.path.join(self._sandbox,'')
  310. self._exceptions = [
  311. os.path.normcase(os.path.realpath(path))
  312. for path in exceptions
  313. ]
  314. AbstractSandbox.__init__(self)
  315. def _violation(self, operation, *args, **kw):
  316. raise SandboxViolation(operation, args, kw)
  317. if _file:
  318. def _file(self, path, mode='r', *args, **kw):
  319. if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
  320. self._violation("file", path, mode, *args, **kw)
  321. return _file(path,mode,*args,**kw)
  322. def _open(self, path, mode='r', *args, **kw):
  323. if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):
  324. self._violation("open", path, mode, *args, **kw)
  325. return _open(path,mode,*args,**kw)
  326. def tmpnam(self):
  327. self._violation("tmpnam")
  328. def _ok(self, path):
  329. active = self._active
  330. try:
  331. self._active = False
  332. realpath = os.path.normcase(os.path.realpath(path))
  333. return (
  334. self._exempted(realpath)
  335. or realpath == self._sandbox
  336. or realpath.startswith(self._prefix)
  337. )
  338. finally:
  339. self._active = active
  340. def _exempted(self, filepath):
  341. start_matches = (
  342. filepath.startswith(exception)
  343. for exception in self._exceptions
  344. )
  345. pattern_matches = (
  346. re.match(pattern, filepath)
  347. for pattern in self._exception_patterns
  348. )
  349. candidates = itertools.chain(start_matches, pattern_matches)
  350. return any(candidates)
  351. def _remap_input(self, operation, path, *args, **kw):
  352. """Called for path inputs"""
  353. if operation in self.write_ops and not self._ok(path):
  354. self._violation(operation, os.path.realpath(path), *args, **kw)
  355. return path
  356. def _remap_pair(self, operation, src, dst, *args, **kw):
  357. """Called for path pairs like rename, link, and symlink operations"""
  358. if not self._ok(src) or not self._ok(dst):
  359. self._violation(operation, src, dst, *args, **kw)
  360. return (src,dst)
  361. def open(self, file, flags, mode=0o777, *args, **kw):
  362. """Called for low-level os.open()"""
  363. if flags & WRITE_FLAGS and not self._ok(file):
  364. self._violation("os.open", file, flags, mode, *args, **kw)
  365. return _os.open(file,flags,mode, *args, **kw)
  366. WRITE_FLAGS = functools.reduce(
  367. operator.or_, [getattr(_os, a, 0) for a in
  368. "O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY".split()]
  369. )
  370. class SandboxViolation(DistutilsError):
  371. """A setup script attempted to modify the filesystem outside the sandbox"""
  372. def __str__(self):
  373. return """SandboxViolation: %s%r %s
  374. The package setup script has attempted to modify files on your system
  375. that are not within the EasyInstall build area, and has been aborted.
  376. This package cannot be safely installed by EasyInstall, and may not
  377. support alternate installation locations even if you run its setup
  378. script by hand. Please inform the package's author and the EasyInstall
  379. maintainers to find out if a fix or workaround is available.""" % self.args
  380. #