SupySandbox: revert code changes in b0291ced (only the README should have been commited). Thanks arvind_khadri for the report.

master
Valentin Lorentz 2011-04-25 20:55:05 +02:00
parent 7ed67622f3
commit 1c246ba254
2 changed files with 60 additions and 74 deletions

View File

@ -26,7 +26,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# pysandbox were originally writen by haypo (under the BSD license),
# pysandbox were originally writen by haypo (under the BSD license),
# and fschfsch by Tila (under the WTFPL license).
###
@ -59,50 +59,9 @@ import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from cStringIO import StringIO
class SandboxError(Exception):
pass
class SandboxInterface(object):
"""This is the base class for interfaces between parent and child."""
def __init__(self, pipes):
self._read, self._write = pipes
self._send('print', 'kikoo')
def _send(self, command, data):
assert ' ' not in command
assert ':' not in command
os.write(self._write, '%s:%s\n' % (command, data))
def _get(self):
lines = []
rawData = ''
newData = 'foo'
while newData != '':
newData = os.read(self._read, 256)
rawData += newData
for line in rawData.split('\n'):
if line == '':
continue
lines.append(line.split(':', 1))
return lines
class ChildSide(SandboxInterface):
def __init__(self, pipes):
super(ChildSide, self).__init__(pipes)
sys.stdout = sys.stderr = self
def write(self, data):
self._send('print', data)
def flush(self):
pass
class ParentSide(SandboxInterface):
def daemon(self):
"""Code that needs to be runned while the child is running"""
printed = ''
for command, data in self._get():
if command == 'print':
printed += data
return printed
def createSandboxConfig():
cfg = S.SandboxConfig(
'stdout',
@ -122,19 +81,17 @@ def createSandboxConfig():
'version', 'hexversion', 'version_info')
return cfg
def _evalPython(line, pipes, locals):
interface = ChildSide(pipes)
locals_ = dict(locals)
locals_.update({'interface': interface})
def _evalPython(line, locals):
locals = dict(locals)
try:
if "\n" in line:
raise SyntaxError()
code = compile(line, "<irc>", "single")
except SyntaxError:
code = compile(line, "<irc>", "exec")
exec code in locals_
exec code in locals
def evalPython(line, pipes, locals=None):
def evalPython(line, locals=None):
sandbox = S.Sandbox(config=createSandboxConfig())
if locals is not None:
@ -142,35 +99,67 @@ def evalPython(line, pipes, locals=None):
else:
locals = dict()
try:
sandbox.call(_evalPython, line, pipes, locals)
sandbox.call(_evalPython, line, locals)
except BaseException, e:
print 'Error: [%s] %s' % (e.__class__.__name__, str(e))
except:
print 'Error: <unknown exception>'
sys.stdout.flush()
def childProcess(line, pipes, locals):
def check_output(expr, expected, locals=None):
from cStringIO import StringIO
original_stdout = sys.stdout
try:
output = StringIO()
sys.stdout = output
evalPython(expr, locals)
stdout = output.getvalue()
assert stdout == expected, "%r != %r" % (stdout, expected)
finally:
sys.stdout = original_stdout
def runTests():
# single
check_output('1+1', '2\n')
check_output('1; 2', '1\n2\n')
check_output(
# written in a single line
"prime=lambda n,i=2:"
"False if n%i==0 else prime(n,i+1) if i*i<n else True; "
"prime(17)",
"True\n")
# exec
check_output('def f(): print("hello")\nf()', 'hello\n')
check_output('print 1\nprint 2', '1\n2\n')
check_output('text', "'abc'\n", {'text': 'abc'})
return True
def childProcess(line, w, locals):
# reseed after a fork to avoid generating the same sequence for each child
random.seed()
sys.stdout = sys.stderr = os.fdopen(w, 'w')
R.setrlimit(R.RLIMIT_CPU, (EVAL_MAXTIMESECONDS, EVAL_MAXTIMESECONDS))
R.setrlimit(R.RLIMIT_AS, (EVAL_MAXMEMORYBYTES, EVAL_MAXMEMORYBYTES))
R.setrlimit(R.RLIMIT_NPROC, (0, 0)) # 0 forks
evalPython(line, pipes, locals)
evalPython(line, locals)
def handleChild(childpid, pipes):
def handleChild(childpid, r):
txt = ''
if __import__("__builtin__").any(select.select([r], [], [], TIMEOUT)):
txt = os.read(r, OUT_MAXLEN + 1)
os.close(r)
n = 0
interface = ParentSide(pipes)
while n < 20:
while n < 6:
pid, status = os.waitpid(childpid, os.WNOHANG)
if pid:
break
time.sleep(.1)
time.sleep(.5)
n += 1
txt += interface.daemon()
if not pid:
os.kill(childpid, signal.SIGKILL)
raise SandboxError('Timeout')
@ -180,23 +169,15 @@ def handleChild(childpid, pipes):
raise SandboxError('Killed')
def handle_line(line):
childToParent = os.pipe()
parentToChild = os.pipe()
child = (childToParent[0], parentToChild[1])
parent = (parentToChild[0], childToParent[1])
del childToParent, parentToChild
r, w = os.pipe()
childpid = os.fork()
if not childpid:
pipes = child
os.close(parent[0])
os.close(parent[1])
childProcess(line, pipes, {})
os.close(r)
childProcess(line, w, {})
os._exit(0)
else:
pipes = parent
os.close(child[0])
os.close(child[1])
result = handleChild(childpid, pipes)
os.close(w)
result = handleChild(childpid, r)
return result
class SupySandbox(callbacks.Plugin):
@ -204,15 +185,20 @@ class SupySandbox(callbacks.Plugin):
This should describe *how* to use this plugin."""
_parser = re.compile(r'(.*sandbox)? (?P<code>.*)')
_parser = re.compile(r'(.?sandbox)? (?P<code>.*)')
def sandbox(self, irc, msg, args):
"""<code>
Runs Python code safely thanks to pysandbox"""
code = self._parser.match(msg.args[1]).group('code')
try:
irc.reply(handle_line(code.replace(' $$ ', '\n')))
except SandboxError, e:
irc.error('; '.join(e.args))
def runtests(self, irc, msg, args):
irc.reply(runTests())
Class = SupySandbox

View File

@ -34,6 +34,9 @@ from supybot.test import *
class SupySandboxTestCase(PluginTestCase):
plugins = ('SupySandbox',)
def testFschfschTestcase(self):
self.assertResponse('runtests', 'True')
def testCodeIsSuccessfullyRunned(self):
self.assertResponse('sandbox 1+1', "2")
self.assertResponse('sandbox print 1+1', "2")
@ -47,10 +50,7 @@ class SupySandboxTestCase(PluginTestCase):
def testProtections(self):
self.assertError('sandbox while True: pass')
self.assertError('sandbox foo="bar"; $$ while True: foo=foo*10')
def testTmp(self):
self.assertResponse('sandbox print foo', 'bar')
self.assertError('sandbox foo="bar"; $$ while True:foo=foo*10')
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: