~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: mattgiuca
  • Date: 2007-12-06 22:11:26 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:8
doc: Added directory "notes", with all the design and research I've done so
    far.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# IVLE
2
 
# Copyright (C) 2007-2008 The University of Melbourne
3
 
#
4
 
# This program is free software; you can redistribute it and/or modify
5
 
# it under the terms of the GNU General Public License as published by
6
 
# the Free Software Foundation; either version 2 of the License, or
7
 
# (at your option) any later version.
8
 
#
9
 
# This program is distributed in the hope that it will be useful,
10
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 
# GNU General Public License for more details.
13
 
#
14
 
# You should have received a copy of the GNU General Public License
15
 
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
 
 
18
 
# Module: Interpret
19
 
# Author: Matt Giuca
20
 
# Date: 18/1/2008
21
 
 
22
 
# Runs a student script in a safe execution environment.
23
 
 
24
 
import ivle
25
 
from ivle import studpath
26
 
from ivle.util import IVLEJailError, split_path
27
 
 
28
 
import functools
29
 
 
30
 
import os
31
 
import pwd
32
 
import subprocess
33
 
import cgi
34
 
 
35
 
# TODO: Make progressive output work
36
 
# Question: Will having a large buffer size stop progressive output from
37
 
# working on smaller output
38
 
 
39
 
CGI_BLOCK_SIZE = 65535
40
 
PATH = "/usr/local/bin:/usr/bin:/bin"
41
 
 
42
 
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
43
 
    """Serves a file by interpreting it using one of IVLE's builtin
44
 
    interpreters. All interpreters are intended to run in the user's jail. The
45
 
    jail location is provided as an argument to the interpreter but it is up
46
 
    to the individual interpreters to create the jail.
47
 
 
48
 
    req: An IVLE request object.
49
 
    owner: The user who owns the file being served.
50
 
    jail_dir: Absolute path to the user's jail.
51
 
    filename: Absolute filename within the user's jail.
52
 
    interpreter: A function object to call.
53
 
    """
54
 
    # We can't test here whether or not the target file actually exists,
55
 
    # because the apache user may not have permission. Instead we have to
56
 
    # rely on the interpreter generating an error.
57
 
    if filename.startswith(os.sep):
58
 
        filename_abs = filename
59
 
        filename_rel = filename[1:]
60
 
    else:
61
 
        filename_abs = os.path.join(os.sep, filename)
62
 
        filename_rel = filename
63
 
 
64
 
    # (Note: files are executed by their owners, not the logged in user.
65
 
    # This ensures users are responsible for their own programs and also
66
 
    # allows them to be executed by the public).
67
 
 
68
 
    # Split up req.path again, this time with respect to the jail
69
 
    (working_dir, _) = os.path.split(filename_abs)
70
 
    # jail_dir is the absolute jail directory.
71
 
    # path is the filename relative to the user's jail.
72
 
    # working_dir is the directory containing the file relative to the user's
73
 
    # jail.
74
 
    # (Note that paths "relative" to the jail actually begin with a '/' as
75
 
    # they are absolute in the jailspace)
76
 
 
77
 
    return interpreter(owner, jail_dir, working_dir, filename_abs, req,
78
 
                       gentle)
79
 
 
80
 
class CGIFlags:
81
 
    """Stores flags regarding the state of reading CGI output.
82
 
       If this is to be gentle, detection of invalid headers will result in an
83
 
       HTML warning."""
84
 
    def __init__(self, begentle=True):
85
 
        self.gentle = begentle
86
 
        self.started_cgi_body = False
87
 
        self.got_cgi_headers = False
88
 
        self.wrote_html_warning = False
89
 
        self.linebuf = ""
90
 
        self.headers = {}       # Header names : values
91
 
 
92
 
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
93
 
                req, gentle):
94
 
    """
95
 
    trampoline: Full path on the local system to the CGI wrapper program
96
 
        being executed.
97
 
    owner: User object of the owner of the file.
98
 
    jail_dir: Absolute path of owner's jail directory.
99
 
    working_dir: Directory containing the script file relative to owner's
100
 
        jail.
101
 
    script_path: CGI script relative to the owner's jail.
102
 
    req: IVLE request object.
103
 
 
104
 
    The called CGI wrapper application shall be called using popen and receive
105
 
    the HTTP body on stdin. It shall receive the CGI environment variables to
106
 
    its environment.
107
 
    """
108
 
 
109
 
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
110
 
 
111
 
    # Support no-op trampoline runs.
112
 
    if interpreter is None:
113
 
        interpreter = '/bin/true'
114
 
        script_path = ''
115
 
        noop = True
116
 
    else:
117
 
        noop = False
118
 
 
119
 
    # Get the student program's directory and execute it from that context.
120
 
    (tramp_dir, _) = os.path.split(trampoline)
121
 
 
122
 
    # TODO: Don't create a file if the body length is known to be 0
123
 
    # Write the HTTP body to a temporary file so it can be passed as a *real*
124
 
    # file to popen.
125
 
    f = os.tmpfile()
126
 
    body = req.read() if not noop else None
127
 
    if body is not None:
128
 
        f.write(body)
129
 
        f.flush()
130
 
        f.seek(0)       # Rewind, for reading
131
 
 
132
 
    # Set up the environment
133
 
    environ = cgi_environ(req, script_path, owner)
134
 
 
135
 
    # usage: tramp uid jail_dir working_dir script_path
136
 
    cmd_line = [trampoline, str(owner.unixid),
137
 
            req.config['paths']['jails']['mounts'],
138
 
            req.config['paths']['jails']['src'],
139
 
            req.config['paths']['jails']['template'],
140
 
            jail_dir, working_dir, interpreter, script_path]
141
 
    # Popen doesn't like unicode strings. It hateses them.
142
 
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
143
 
                for s in cmd_line]
144
 
    pid = subprocess.Popen(cmd_line,
145
 
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
146
 
        cwd=tramp_dir, env=environ)
147
 
 
148
 
    # We don't want any output! Bail out after the process terminates.
149
 
    if noop:
150
 
        pid.communicate()
151
 
        return
152
 
 
153
 
    # process_cgi_line: Reads a single line of CGI output and processes it.
154
 
    # Prints to req, and also does fancy HTML warnings if Content-Type
155
 
    # omitted.
156
 
    cgiflags = CGIFlags(gentle)
157
 
 
158
 
    # Read from the process's stdout into req
159
 
    data = pid.stdout.read(CGI_BLOCK_SIZE)
160
 
    while len(data) > 0:
161
 
        process_cgi_output(req, data, cgiflags)
162
 
        data = pid.stdout.read(CGI_BLOCK_SIZE)
163
 
 
164
 
    # If we haven't processed headers yet, now is a good time
165
 
    if not cgiflags.started_cgi_body:
166
 
        process_cgi_output(req, '\n', cgiflags)
167
 
 
168
 
    # If we wrote an HTML warning header, write the footer
169
 
    if cgiflags.wrote_html_warning:
170
 
        req.write("""</pre>
171
 
  </div>
172
 
</body>
173
 
</html>""")
174
 
 
175
 
def process_cgi_output(req, data, cgiflags):
176
 
    """Processes a chunk of CGI output. data is a string of arbitrary length;
177
 
    some arbitrary chunk of output written by the CGI script."""
178
 
    if cgiflags.started_cgi_body:
179
 
        if cgiflags.wrote_html_warning:
180
 
            # HTML escape text if wrote_html_warning
181
 
            req.write(cgi.escape(data))
182
 
        else:
183
 
            req.write(data)
184
 
    else:
185
 
        # Break data into lines of CGI header data. 
186
 
        linebuf = cgiflags.linebuf + data
187
 
        # First see if we can split all header data
188
 
        # We need to get the double CRLF- or LF-terminated headers, whichever
189
 
        # is smaller, as either sequence may appear somewhere in the body.
190
 
        usplit = linebuf.split('\n\n', 1)
191
 
        wsplit = linebuf.split('\r\n\r\n', 1)
192
 
        split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
193
 
        if len(split) == 1:
194
 
            # Haven't seen all headers yet. Buffer and come back later.
195
 
            cgiflags.linebuf = linebuf
196
 
            return
197
 
 
198
 
        headers = split[0]
199
 
        data = split[1]
200
 
        cgiflags.linebuf = ""
201
 
        cgiflags.started_cgi_body = True
202
 
        # Process all the header lines
203
 
        split = headers.split('\r\n', 1)
204
 
        if len(split) == 1:
205
 
            split = headers.split('\n', 1)
206
 
        while True:
207
 
            process_cgi_header_line(req, split[0], cgiflags)
208
 
            if len(split) == 1: break
209
 
            headers = split[1]
210
 
            if cgiflags.wrote_html_warning:
211
 
                # We're done with headers. Treat the rest as data.
212
 
                data = headers + '\n' + data
213
 
                break
214
 
            split = headers.split('\r\n', 1)
215
 
            if len(split) == 1:
216
 
                split = headers.split('\n', 1)
217
 
 
218
 
        # Is this an internal IVLE error condition?
219
 
        hs = cgiflags.headers
220
 
        if 'X-IVLE-Error-Type' in hs:
221
 
            try:
222
 
                raise IVLEJailError(hs['X-IVLE-Error-Type'],
223
 
                                    hs['X-IVLE-Error-Message'],
224
 
                                    hs['X-IVLE-Error-Info'])
225
 
            except KeyError:
226
 
                raise AssertionError("Bad error headers written by CGI.")
227
 
 
228
 
        # Check to make sure the required headers were written
229
 
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
230
 
            # We already reported an error, that's enough
231
 
            pass
232
 
        elif "Content-Type" in cgiflags.headers:
233
 
            pass
234
 
        elif "Location" in cgiflags.headers:
235
 
            if ("Status" in cgiflags.headers and req.status >= 300
236
 
                and req.status < 400):
237
 
                pass
238
 
            else:
239
 
                message = """You did not write a valid status code for
240
 
the given location. To make a redirect, you may wish to try:</p>
241
 
<pre style="margin-left: 1em">Status: 302 Found
242
 
Location: &lt;redirect address&gt;</pre>"""
243
 
                write_html_warning(req, message)
244
 
                cgiflags.wrote_html_warning = True
245
 
        else:
246
 
            message = """You did not print a Content-Type header.
247
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
248
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
249
 
            write_html_warning(req, message)
250
 
            cgiflags.wrote_html_warning = True
251
 
 
252
 
        # Call myself to flush out the extra bit of data we read
253
 
        process_cgi_output(req, data, cgiflags)
254
 
 
255
 
def process_cgi_header_line(req, line, cgiflags):
256
 
    """Process a line of CGI header data. line is a string representing a
257
 
    complete line of text, stripped and without the newline.
258
 
    """
259
 
    try:
260
 
        name, value = line.split(':', 1)
261
 
    except ValueError:
262
 
        # No colon. The user did not write valid headers.
263
 
        # If we are being gentle, we want to help the user understand what
264
 
        # went wrong. Otherwise, just admit we screwed up.
265
 
        warning = "Warning"
266
 
        if not cgiflags.gentle:
267
 
            message = """An unexpected server error has occured."""
268
 
            warning = "Error"
269
 
        elif len(cgiflags.headers) == 0:
270
 
            # First line was not a header line. We can assume this is not
271
 
            # a CGI app.
272
 
            message = """You did not print a CGI header.
273
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
274
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
275
 
        else:
276
 
            # They printed some header at least, but there was an invalid
277
 
            # header.
278
 
            message = """You printed an invalid CGI header. You need to leave
279
 
a blank line after the headers, before writing the page contents."""
280
 
        write_html_warning(req, message, warning=warning)
281
 
        cgiflags.wrote_html_warning = True
282
 
        # Handle the rest of this line as normal data
283
 
        process_cgi_output(req, line + '\n', cgiflags)
284
 
        return
285
 
 
286
 
    # Read CGI headers
287
 
    value = value.strip()
288
 
    if name == "Content-Type":
289
 
        req.content_type = value
290
 
    elif name == "Location":
291
 
        req.location = value
292
 
    elif name == "Status":
293
 
        # Must be an integer, followed by a space, and then the status line
294
 
        # which we ignore (seems like Apache has no way to send a custom
295
 
        # status line).
296
 
        try:
297
 
            req.status = int(value.split(' ', 1)[0])
298
 
        except ValueError:
299
 
            if not cgiflags.gentle:
300
 
                # This isn't user code, so it should be good.
301
 
                # Get us out of here!
302
 
                raise
303
 
            message = """The "Status" CGI header was invalid. You need to
304
 
print a number followed by a message, such as "302 Found"."""
305
 
            write_html_warning(req, message)
306
 
            cgiflags.wrote_html_warning = True
307
 
            # Handle the rest of this line as normal data
308
 
            process_cgi_output(req, line + '\n', cgiflags)
309
 
    else:
310
 
        # Generic HTTP header
311
 
        # FIXME: Security risk letting users write arbitrary headers?
312
 
        req.headers_out.add(name, value)
313
 
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
314
 
 
315
 
def write_html_warning(req, text, warning="Warning"):
316
 
    """Prints an HTML warning about invalid CGI interaction on the part of the
317
 
    user. text may contain HTML markup."""
318
 
    req.content_type = "text/html"
319
 
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
320
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
321
 
<html xmlns="http://www.w3.org/1999/xhtml">
322
 
<head>
323
 
  <meta http-equiv="Content-Type"
324
 
    content="text/html; charset=utf-8" />
325
 
</head>
326
 
<body style="margin: 0; padding: 0; font-family: sans-serif;">
327
 
  <div style="background-color: #faa; border-bottom: 1px solid black;
328
 
    padding: 8px;">
329
 
    <p><strong>%s</strong>: %s
330
 
  </div>
331
 
  <div style="margin: 8px;">
332
 
    <pre>
333
 
""" % (warning, text))
334
 
 
335
 
# Mapping of interpreter names (as given in conf/app/server.py) to
336
 
# interpreter functions.
337
 
 
338
 
interpreter_objects = {
339
 
    'cgi-python'
340
 
        : functools.partial(execute_cgi, "/usr/bin/python"),
341
 
    'noop'
342
 
        : functools.partial(execute_cgi, None),
343
 
    # Should also have:
344
 
    # cgi-generic
345
 
    # python-server-page
346
 
}
347
 
 
348
 
def cgi_environ(req, script_path, user):
349
 
    """Gets CGI variables from apache and makes a few changes for security and 
350
 
    correctness.
351
 
 
352
 
    Does not modify req, only reads it.
353
 
    """
354
 
    env = {}
355
 
    # Comments here are on the heavy side, explained carefully for security
356
 
    # reasons. Please read carefully before making changes.
357
 
    
358
 
    # This automatically asks mod_python to load up the CGI variables into the
359
 
    # environment (which is a good first approximation)
360
 
    for (k,v) in req.get_cgi_environ().items():
361
 
        env[k] = v
362
 
 
363
 
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
364
 
    # exposes unnecessary details about server.
365
 
    try:
366
 
        del env['DOCUMENT_ROOT']
367
 
    except: pass
368
 
    try:
369
 
        del env['SCRIPT_FILENAME']
370
 
    except: pass
371
 
 
372
 
    # Remove PATH. The PATH here is the path on the server machine; not useful
373
 
    # inside the jail. It may be a good idea to add another path, reflecting
374
 
    # the inside of the jail, but not done at this stage.
375
 
    try:
376
 
        del env['PATH']
377
 
    except: pass
378
 
 
379
 
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
380
 
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
381
 
    # REMOTE_ADDR.
382
 
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
383
 
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
384
 
 
385
 
    env['PATH_INFO'] = ''
386
 
    del env['PATH_TRANSLATED']
387
 
 
388
 
    normuri = os.path.normpath(req.uri)
389
 
    env['SCRIPT_NAME'] = normuri
390
 
 
391
 
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
392
 
    # We don't care about these if the script is null (ie. noop).
393
 
    # XXX: We check for /home because we don't want to interfere with
394
 
    # CGIRequest, which fileservice still uses.
395
 
    if script_path and script_path.startswith('/home'):
396
 
        normscript = os.path.normpath(script_path)
397
 
 
398
 
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
399
 
 
400
 
        # PATH_INFO is wrong because the script doesn't physically exist.
401
 
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
402
 
        if len(env['PATH_INFO']) > 0:
403
 
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
404
 
 
405
 
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
406
 
    # custom-making the CGI request.
407
 
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
408
 
 
409
 
    # Additional environment variables
410
 
    username = user.login
411
 
    env['HOME'] = os.path.join('/home', username)
412
 
 
413
 
    return env
414
 
 
415
 
class ExecutionError(Exception):
416
 
    pass
417
 
 
418
 
def execute_raw(config, user, jail_dir, working_dir, binary, args):
419
 
    '''Execute a binary in a user's jail, returning the raw output.
420
 
 
421
 
    The binary is executed in the given working directory with the given
422
 
    args. A tuple of (stdout, stderr) is returned.
423
 
    '''
424
 
 
425
 
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
426
 
    tramp_dir = os.path.split(tramp)[0]
427
 
 
428
 
    # Fire up trampoline. Vroom, vroom.
429
 
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
430
 
         config['paths']['jails']['src'],
431
 
         config['paths']['jails']['template'],
432
 
         jail_dir, working_dir, binary] + args
433
 
    # Popen doesn't like unicode strings. It hateses them.
434
 
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
435
 
                for s in cmd_line]
436
 
    proc = subprocess.Popen(cmd_line,
437
 
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
438
 
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
439
 
        env={'HOME': os.path.join('/home', user.login),
440
 
             'PATH': PATH,
441
 
             'USER': user.login,
442
 
             'LOGNAME': user.login})
443
 
 
444
 
    (stdout, stderr) = proc.communicate()
445
 
    exitcode = proc.returncode
446
 
 
447
 
    if exitcode != 0:
448
 
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
449
 
                             (exitcode, stderr))
450
 
    return (stdout, stderr)