-
Notifications
You must be signed in to change notification settings - Fork 38
/
compile.py
215 lines (190 loc) · 6.76 KB
/
compile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import ast
import warnings
from collections import namedtuple
from RestrictedPython._compat import IS_CPYTHON
from RestrictedPython._compat import IS_PY2
from RestrictedPython.transformer import RestrictingNodeTransformer
CompileResult = namedtuple(
'CompileResult', 'code, errors, warnings, used_names')
syntax_error_template = (
'Line {lineno}: {type}: {msg} at statement: {statement!r}')
NOT_CPYTHON_WARNING = (
'RestrictedPython is only supported on CPython: use on other Python '
'implementations may create security issues.'
)
def _compile_restricted_mode(
source,
filename='<string>',
mode="exec",
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
if not IS_CPYTHON:
warnings.warn_explicit(
NOT_CPYTHON_WARNING, RuntimeWarning, 'RestrictedPython', 0)
byte_code = None
collected_errors = []
collected_warnings = []
used_names = {}
if policy is None:
# Unrestricted Source Checks
byte_code = compile(source, filename, mode=mode, flags=flags,
dont_inherit=dont_inherit)
elif issubclass(policy, RestrictingNodeTransformer):
c_ast = None
allowed_source_types = [str, ast.Module]
if IS_PY2: # pragma: PY2
allowed_source_types.append(unicode) # NOQA: F821,E501 # PY2 only statement, in Python 2 only module
if not issubclass(type(source), tuple(allowed_source_types)):
raise TypeError('Not allowed source type: '
'"{0.__class__.__name__}".'.format(source))
c_ast = None
# workaround for pypy issue https://bitbucket.org/pypy/pypy/issues/2552
if isinstance(source, ast.Module):
c_ast = source
else:
try:
c_ast = ast.parse(source, filename, mode)
except (TypeError, ValueError) as e:
collected_errors.append(str(e))
except SyntaxError as v:
collected_errors.append(syntax_error_template.format(
lineno=v.lineno,
type=v.__class__.__name__,
msg=v.msg,
statement=v.text.strip() if v.text else None
))
if c_ast:
policy_instance = policy(
collected_errors, collected_warnings, used_names)
policy_instance.visit(c_ast)
if not collected_errors:
byte_code = compile(c_ast, filename, mode=mode # ,
# flags=flags,
# dont_inherit=dont_inherit
)
else:
raise TypeError('Unallowed policy provided for RestrictedPython')
return CompileResult(
byte_code,
tuple(collected_errors),
collected_warnings,
used_names)
def compile_restricted_exec(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
"""Compile restricted for the mode `exec`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='exec',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
def compile_restricted_eval(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
"""Compile restricted for the mode `eval`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='eval',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
def compile_restricted_single(
source,
filename='<string>',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
"""Compile restricted for the mode `single`."""
return _compile_restricted_mode(
source,
filename=filename,
mode='single',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
def compile_restricted_function(
p, # parameters
body,
name,
filename='<string>',
globalize=None, # List of globals (e.g. ['here', 'context', ...])
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
"""Compile a restricted code object for a function.
Documentation see:
http://restrictedpython.readthedocs.io/en/latest/usage/index.html#RestrictedPython.compile_restricted_function
"""
# Parse the parameters and body, then combine them.
try:
body_ast = ast.parse(body, '<func code>', 'exec')
except SyntaxError as v:
error = syntax_error_template.format(
lineno=v.lineno,
type=v.__class__.__name__,
msg=v.msg,
statement=v.text.strip() if v.text else None)
return CompileResult(
code=None, errors=(error,), warnings=(), used_names=())
# The compiled code is actually executed inside a function
# (that is called when the code is called) so reading and assigning to a
# global variable like this`printed += 'foo'` would throw an
# UnboundLocalError.
# We don't want the user to need to understand this.
if globalize:
body_ast.body.insert(0, ast.Global(globalize))
wrapper_ast = ast.parse('def masked_function_name(%s): pass' % p,
'<func wrapper>', 'exec')
# In case the name you chose for your generated function is not a
# valid python identifier we set it after the fact
function_ast = wrapper_ast.body[0]
assert isinstance(function_ast, ast.FunctionDef)
function_ast.name = name
wrapper_ast.body[0].body = body_ast.body
wrapper_ast = ast.fix_missing_locations(wrapper_ast)
result = _compile_restricted_mode(
wrapper_ast,
filename=filename,
mode='exec',
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
return result
def compile_restricted(
source,
filename='<unknown>',
mode='exec',
flags=0,
dont_inherit=False,
policy=RestrictingNodeTransformer):
"""Replacement for the built-in compile() function.
policy ... `ast.NodeTransformer` class defining the restrictions.
"""
if mode in ['exec', 'eval', 'single', 'function']:
result = _compile_restricted_mode(
source,
filename=filename,
mode=mode,
flags=flags,
dont_inherit=dont_inherit,
policy=policy)
else:
raise TypeError('unknown mode %s', mode)
for warning in result.warnings:
warnings.warn(
warning,
SyntaxWarning
)
if result.errors:
raise SyntaxError(result.errors)
return result.code