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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: mattgiuca
  • Date: 2008-01-12 15:35:53 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:201
Added "test" directory.
Added make_date_test.py, a short script I wrote to test the date format
algorithm committed in the previous revision.

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)
138
 
 
139
 
    # usage: tramp uid jail_dir working_dir script_path
140
 
    pid = subprocess.Popen(
141
 
        [trampoline, str(uid), jail_dir, working_dir, interpreter,
142
 
        script_path],
143
 
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
144
 
        cwd=tramp_dir)
145
 
 
146
 
    # Restore the environment
147
 
    for k in os.environ.keys():
148
 
        del os.environ[k]
149
 
    for (k,v) in old_env.items():
150
 
        os.environ[k] = v
151
 
 
152
 
    # We don't want any output! Bail out after the process terminates.
153
 
    if noop:
154
 
        pid.communicate()
155
 
        return
156
 
 
157
 
    # process_cgi_line: Reads a single line of CGI output and processes it.
158
 
    # Prints to req, and also does fancy HTML warnings if Content-Type
159
 
    # omitted.
160
 
    cgiflags = CGIFlags(gentle)
161
 
 
162
 
    # Read from the process's stdout into req
163
 
    data = pid.stdout.read(CGI_BLOCK_SIZE)
164
 
    while len(data) > 0:
165
 
        process_cgi_output(req, data, cgiflags)
166
 
        data = pid.stdout.read(CGI_BLOCK_SIZE)
167
 
 
168
 
    # If we haven't processed headers yet, now is a good time
169
 
    if not cgiflags.started_cgi_body:
170
 
        process_cgi_output(req, '\n', cgiflags)
171
 
 
172
 
    # If we wrote an HTML warning header, write the footer
173
 
    if cgiflags.wrote_html_warning:
174
 
        req.write("""</pre>
175
 
  </div>
176
 
</body>
177
 
</html>""")
178
 
 
179
 
def process_cgi_output(req, data, cgiflags):
180
 
    """Processes a chunk of CGI output. data is a string of arbitrary length;
181
 
    some arbitrary chunk of output written by the CGI script."""
182
 
    if cgiflags.started_cgi_body:
183
 
        if cgiflags.wrote_html_warning:
184
 
            # HTML escape text if wrote_html_warning
185
 
            req.write(cgi.escape(data))
186
 
        else:
187
 
            req.write(data)
188
 
    else:
189
 
        # Break data into lines of CGI header data. 
190
 
        linebuf = cgiflags.linebuf + data
191
 
        # First see if we can split all header data
192
 
        # We need to get the double CRLF- or LF-terminated headers, whichever
193
 
        # is smaller, as either sequence may appear somewhere in the body.
194
 
        usplit = linebuf.split('\n\n', 1)
195
 
        wsplit = linebuf.split('\r\n\r\n', 1)
196
 
        split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
197
 
        if len(split) == 1:
198
 
            # Haven't seen all headers yet. Buffer and come back later.
199
 
            cgiflags.linebuf = linebuf
200
 
            return
201
 
 
202
 
        headers = split[0]
203
 
        data = split[1]
204
 
        cgiflags.linebuf = ""
205
 
        cgiflags.started_cgi_body = True
206
 
        # Process all the header lines
207
 
        split = headers.split('\r\n', 1)
208
 
        if len(split) == 1:
209
 
            split = headers.split('\n', 1)
210
 
        while True:
211
 
            process_cgi_header_line(req, split[0], cgiflags)
212
 
            if len(split) == 1: break
213
 
            headers = split[1]
214
 
            if cgiflags.wrote_html_warning:
215
 
                # We're done with headers. Treat the rest as data.
216
 
                data = headers + '\n' + data
217
 
                break
218
 
            split = headers.split('\r\n', 1)
219
 
            if len(split) == 1:
220
 
                split = headers.split('\n', 1)
221
 
 
222
 
        # Is this an internal IVLE error condition?
223
 
        hs = cgiflags.headers
224
 
        if 'X-IVLE-Error-Type' in hs:
225
 
            t = hs['X-IVLE-Error-Type']
226
 
            if t == IVLEError.__name__:
227
 
                raise IVLEError(int(hs['X-IVLE-Error-Code']),
228
 
                                hs['X-IVLE-Error-Message'])
229
 
            else:
230
 
                try:
231
 
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
232
 
                                        hs['X-IVLE-Error-Message'],
233
 
                                        hs['X-IVLE-Error-Info'])
234
 
                except KeyError:
235
 
                    raise IVLEError(500, 'bad error headers written by CGI')
236
 
 
237
 
        # Check to make sure the required headers were written
238
 
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
239
 
            # We already reported an error, that's enough
240
 
            pass
241
 
        elif "Content-Type" in cgiflags.headers:
242
 
            pass
243
 
        elif "Location" in cgiflags.headers:
244
 
            if ("Status" in cgiflags.headers and req.status >= 300
245
 
                and req.status < 400):
246
 
                pass
247
 
            else:
248
 
                message = """You did not write a valid status code for
249
 
the given location. To make a redirect, you may wish to try:</p>
250
 
<pre style="margin-left: 1em">Status: 302 Found
251
 
Location: &lt;redirect address&gt;</pre>"""
252
 
                write_html_warning(req, message)
253
 
                cgiflags.wrote_html_warning = True
254
 
        else:
255
 
            message = """You did not print a Content-Type header.
256
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
257
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
258
 
            write_html_warning(req, message)
259
 
            cgiflags.wrote_html_warning = True
260
 
 
261
 
        # Call myself to flush out the extra bit of data we read
262
 
        process_cgi_output(req, data, cgiflags)
263
 
 
264
 
def process_cgi_header_line(req, line, cgiflags):
265
 
    """Process a line of CGI header data. line is a string representing a
266
 
    complete line of text, stripped and without the newline.
267
 
    """
268
 
    try:
269
 
        name, value = line.split(':', 1)
270
 
    except ValueError:
271
 
        # No colon. The user did not write valid headers.
272
 
        # If we are being gentle, we want to help the user understand what
273
 
        # went wrong. Otherwise, just admit we screwed up.
274
 
        warning = "Warning"
275
 
        if not cgiflags.gentle:
276
 
            message = """An unexpected server error has occured."""
277
 
            warning = "Error"
278
 
        elif len(cgiflags.headers) == 0:
279
 
            # First line was not a header line. We can assume this is not
280
 
            # a CGI app.
281
 
            message = """You did not print a CGI header.
282
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
283
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
284
 
        else:
285
 
            # They printed some header at least, but there was an invalid
286
 
            # header.
287
 
            message = """You printed an invalid CGI header. You need to leave
288
 
a blank line after the headers, before writing the page contents."""
289
 
        write_html_warning(req, message, warning=warning)
290
 
        cgiflags.wrote_html_warning = True
291
 
        # Handle the rest of this line as normal data
292
 
        process_cgi_output(req, line + '\n', cgiflags)
293
 
        return
294
 
 
295
 
    # Read CGI headers
296
 
    value = value.strip()
297
 
    if name == "Content-Type":
298
 
        req.content_type = value
299
 
    elif name == "Location":
300
 
        req.location = value
301
 
    elif name == "Status":
302
 
        # Must be an integer, followed by a space, and then the status line
303
 
        # which we ignore (seems like Apache has no way to send a custom
304
 
        # status line).
305
 
        try:
306
 
            req.status = int(value.split(' ', 1)[0])
307
 
        except ValueError:
308
 
            if not cgiflags.gentle:
309
 
                # This isn't user code, so it should be good.
310
 
                # Get us out of here!
311
 
                raise
312
 
            message = """The "Status" CGI header was invalid. You need to
313
 
print a number followed by a message, such as "302 Found"."""
314
 
            write_html_warning(req, message)
315
 
            cgiflags.wrote_html_warning = True
316
 
            # Handle the rest of this line as normal data
317
 
            process_cgi_output(req, line + '\n', cgiflags)
318
 
    else:
319
 
        # Generic HTTP header
320
 
        # FIXME: Security risk letting users write arbitrary headers?
321
 
        req.headers_out.add(name, value)
322
 
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
323
 
 
324
 
def write_html_warning(req, text, warning="Warning"):
325
 
    """Prints an HTML warning about invalid CGI interaction on the part of the
326
 
    user. text may contain HTML markup."""
327
 
    req.content_type = "text/html"
328
 
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
329
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
330
 
<html xmlns="http://www.w3.org/1999/xhtml">
331
 
<head>
332
 
  <meta http-equiv="Content-Type"
333
 
    content="text/html; charset=utf-8" />
334
 
</head>
335
 
<body style="margin: 0; padding: 0; font-family: sans-serif;">
336
 
  <div style="background-color: #faa; border-bottom: 1px solid black;
337
 
    padding: 8px;">
338
 
    <p><strong>%s</strong>: %s
339
 
  </div>
340
 
  <div style="margin: 8px;">
341
 
    <pre>
342
 
""" % (warning, text))
343
 
 
344
 
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
345
 
 
346
 
# Mapping of interpreter names (as given in conf/app/server.py) to
347
 
# interpreter functions.
348
 
 
349
 
interpreter_objects = {
350
 
    'cgi-python'
351
 
        : functools.partial(execute_cgi, "/usr/bin/python",
352
 
            location_cgi_python),
353
 
    'noop'
354
 
        : functools.partial(execute_cgi, None,
355
 
            location_cgi_python),
356
 
    # Should also have:
357
 
    # cgi-generic
358
 
    # python-server-page
359
 
}
360
 
 
361
 
def fixup_environ(req):
362
 
    """Assuming os.environ has been written with the CGI variables from
363
 
    apache, make a few changes for security and correctness.
364
 
 
365
 
    Does not modify req, only reads it.
366
 
    """
367
 
    env = os.environ
368
 
    # Comments here are on the heavy side, explained carefully for security
369
 
    # reasons. Please read carefully before making changes.
370
 
 
371
 
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
372
 
    # exposes unnecessary details about server.
373
 
    try:
374
 
        del env['DOCUMENT_ROOT']
375
 
    except: pass
376
 
    try:
377
 
        del env['SCRIPT_FILENAME']
378
 
    except: pass
379
 
 
380
 
    # Remove PATH. The PATH here is the path on the server machine; not useful
381
 
    # inside the jail. It may be a good idea to add another path, reflecting
382
 
    # the inside of the jail, but not done at this stage.
383
 
    try:
384
 
        del env['PATH']
385
 
    except: pass
386
 
 
387
 
    # Remove SCRIPT_FILENAME. Not part of CGI spec (see SCRIPT_NAME).
388
 
 
389
 
    # PATH_INFO is wrong because the script doesn't physically exist.
390
 
    # Apache makes it relative to the "serve" app. It should actually be made
391
 
    # relative to the student's script. intepretservice does that in the jail,
392
 
    # so here we just clear it.
393
 
    env['PATH_INFO'] = ''
394
 
    env['PATH_TRANSLATED'] = ''
395
 
 
396
 
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
397
 
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
398
 
    # REMOTE_ADDR.
399
 
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
400
 
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
401
 
 
402
 
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
403
 
    script_name = req.uri
404
 
    env['SCRIPT_NAME'] = script_name
405
 
 
406
 
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
407
 
    # custom-making the CGI request.
408
 
    env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
409
 
 
410
 
    # Additional environment variables
411
 
    username = studpath.url_to_jailpaths(req.path)[0]
412
 
    env['HOME'] = os.path.join('/home', username)
413
 
 
414
 
class ExecutionError(Exception):
415
 
    pass
416
 
 
417
 
def execute_raw(user, jail_dir, working_dir, binary, args):
418
 
    '''Execute a binary in a user's jail, returning the raw output.
419
 
 
420
 
    The binary is executed in the given working directory with the given
421
 
    args. A tuple of (stdout, stderr) is returned.
422
 
    '''
423
 
 
424
 
    tramp = location_cgi_python
425
 
    tramp_dir = os.path.split(location_cgi_python)[0]
426
 
 
427
 
    # Fire up trampoline. Vroom, vroom.
428
 
    proc = subprocess.Popen(
429
 
        [tramp, str(user.unixid), jail_dir, working_dir, binary] + args,
430
 
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
431
 
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
432
 
    exitcode = proc.wait()
433
 
 
434
 
    if exitcode != 0:
435
 
        raise ExecutionError('subprocess ended with code %d, stderr %s' %
436
 
                             (exitcode, proc.stderr.read()))
437
 
    return (proc.stdout.read(), proc.stderr.read())