sandbox.py 14 KB

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