1 """
2 This file is part of web2py Web Framework (Copyrighted, 2007)
3 Developed by Massimo Di Pierro <mdipierro@cs.depaul.edu>
4 License: GPL v2
5 """
6
7 import sys, cStringIO, cPickle, traceback, copy, cgi, types, time, os
8 from random import random
9 from html import BEAUTIFY
10
11 __all__=['RestrictedError','restricted']
12
14 """
15 class used to wrap an exception that occurs in the restricted environment
16 below. the traceback is used to log the exception and generate a ticket.
17 """
18 - def __init__(self,layer='',code='',output='',environment={}):
19 """
20 layer here is some description of where in the system the exception
21 occurred.
22 """
23 self.layer=layer
24 self.code=code
25 self.output=output
26 if layer: self.traceback=traceback.format_exc()
27 else: self.traceback='(no error)'
28 self.environment=environment
29
30 - def log(self,request):
31 """
32 logs the exeption.
33 """
34 a=request.application
35 d={'layer':str(self.layer),
36 'code':str(self.code),
37 'output':str(self.output),
38 'traceback':str(self.traceback)}
39 f=request.env.remote_addr+'.'+str(int(time.time()))+'.'+str(random())[2:]
40 cPickle.dump(d,open(os.path.join(request.folder,'errors',f),'wb'))
41 return '%s/%s' % (a,f)
42
43 - def load(self,file):
44 """
45 loads a logged exception.
46 """
47 d=cPickle.load(open(file,'rb'))
48 self.layer=d['layer']
49 self.code=d['code']
50 self.output=d['output']
51 self.traceback=d['traceback']
52
53 -def restricted(code,environment={},layer='Unkown'):
54 """
55 runs code in evrionment and returns the output. if an exeception occurs
56 in code it raises a RestrictedError containg the traceback. layer is passed
57 to RestrictedError to identify where the error occurred.
58 """
59 try:
60 if type(code)==types.CodeType: ccode=code
61 else: ccode=compile(code,layer,'exec')
62 exec ccode in environment
63 except BaseException, exception:
64 raise RestrictedError(layer,code,'',environment)
65