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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: drtomc
  • Date: 2007-12-04 01:57:41 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:3
A README file describing sundry bits of the platform infrastructure.

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