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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: drtomc
  • Date: 2007-12-11 03:26:29 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:25
A bit more work on the userdb stuff.

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
 
        # If not executing in gentle mode (which presents CGI violations
219
 
        # to users nicely), check if this an internal IVLE error
220
 
        # condition.
221
 
        if not cgiflags.gentle:
222
 
            hs = cgiflags.headers
223
 
            if 'X-IVLE-Error-Type' in hs:
224
 
                try:
225
 
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
226
 
                                        hs['X-IVLE-Error-Message'],
227
 
                                        hs['X-IVLE-Error-Info'])
228
 
                except KeyError:
229
 
                    raise AssertionError("Bad error headers written by CGI.")
230
 
 
231
 
        # Check to make sure the required headers were written
232
 
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
233
 
            # We already reported an error, that's enough
234
 
            pass
235
 
        elif "Content-Type" in cgiflags.headers:
236
 
            pass
237
 
        elif "Location" in cgiflags.headers:
238
 
            if ("Status" in cgiflags.headers and req.status >= 300
239
 
                and req.status < 400):
240
 
                pass
241
 
            else:
242
 
                message = """You did not write a valid status code for
243
 
the given location. To make a redirect, you may wish to try:</p>
244
 
<pre style="margin-left: 1em">Status: 302 Found
245
 
Location: &lt;redirect address&gt;</pre>"""
246
 
                write_html_warning(req, message)
247
 
                cgiflags.wrote_html_warning = True
248
 
        else:
249
 
            message = """You did not print a Content-Type header.
250
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
251
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
252
 
            write_html_warning(req, message)
253
 
            cgiflags.wrote_html_warning = True
254
 
 
255
 
        # Call myself to flush out the extra bit of data we read
256
 
        process_cgi_output(req, data, cgiflags)
257
 
 
258
 
def process_cgi_header_line(req, line, cgiflags):
259
 
    """Process a line of CGI header data. line is a string representing a
260
 
    complete line of text, stripped and without the newline.
261
 
    """
262
 
    try:
263
 
        name, value = line.split(':', 1)
264
 
    except ValueError:
265
 
        # No colon. The user did not write valid headers.
266
 
        # If we are being gentle, we want to help the user understand what
267
 
        # went wrong. Otherwise, just admit we screwed up.
268
 
        warning = "Warning"
269
 
        if not cgiflags.gentle:
270
 
            message = """An unexpected server error has occured."""
271
 
            warning = "Error"
272
 
        elif len(cgiflags.headers) == 0:
273
 
            # First line was not a header line. We can assume this is not
274
 
            # a CGI app.
275
 
            message = """You did not print a CGI header.
276
 
CGI requires that you print a "Content-Type". You may wish to try:</p>
277
 
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
278
 
        else:
279
 
            # They printed some header at least, but there was an invalid
280
 
            # header.
281
 
            message = """You printed an invalid CGI header. You need to leave
282
 
a blank line after the headers, before writing the page contents."""
283
 
        write_html_warning(req, message, warning=warning)
284
 
        cgiflags.wrote_html_warning = True
285
 
        # Handle the rest of this line as normal data
286
 
        process_cgi_output(req, line + '\n', cgiflags)
287
 
        return
288
 
 
289
 
    # Read CGI headers
290
 
    value = value.strip()
291
 
    if name == "Content-Type":
292
 
        req.content_type = value
293
 
    elif name == "Location":
294
 
        req.location = value
295
 
    elif name == "Status":
296
 
        # Must be an integer, followed by a space, and then the status line
297
 
        # which we ignore (seems like Apache has no way to send a custom
298
 
        # status line).
299
 
        try:
300
 
            req.status = int(value.split(' ', 1)[0])
301
 
        except ValueError:
302
 
            if not cgiflags.gentle:
303
 
                # This isn't user code, so it should be good.
304
 
                # Get us out of here!
305
 
                raise
306
 
            message = """The "Status" CGI header was invalid. You need to
307
 
print a number followed by a message, such as "302 Found"."""
308
 
            write_html_warning(req, message)
309
 
            cgiflags.wrote_html_warning = True
310
 
            # Handle the rest of this line as normal data
311
 
            process_cgi_output(req, line + '\n', cgiflags)
312
 
    else:
313
 
        # Generic HTTP header
314
 
        # FIXME: Security risk letting users write arbitrary headers?
315
 
        req.headers_out.add(name, value)
316
 
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
317
 
 
318
 
def write_html_warning(req, text, warning="Warning"):
319
 
    """Prints an HTML warning about invalid CGI interaction on the part of the
320
 
    user. text may contain HTML markup."""
321
 
    req.content_type = "text/html"
322
 
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
323
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
324
 
<html xmlns="http://www.w3.org/1999/xhtml">
325
 
<head>
326
 
  <meta http-equiv="Content-Type"
327
 
    content="text/html; charset=utf-8" />
328
 
</head>
329
 
<body style="margin: 0; padding: 0; font-family: sans-serif;">
330
 
  <div style="background-color: #faa; border-bottom: 1px solid black;
331
 
    padding: 8px;">
332
 
    <p><strong>%s</strong>: %s
333
 
  </div>
334
 
  <div style="margin: 8px;">
335
 
    <pre>
336
 
""" % (warning, text))
337
 
 
338
 
# Mapping of interpreter names (as given in conf/app/server.py) to
339
 
# interpreter functions.
340
 
 
341
 
interpreter_objects = {
342
 
    'cgi-python'
343
 
        : functools.partial(execute_cgi, "/usr/bin/python"),
344
 
    'noop'
345
 
        : functools.partial(execute_cgi, None),
346
 
    # Should also have:
347
 
    # cgi-generic
348
 
    # python-server-page
349
 
}
350
 
 
351
 
def cgi_environ(req, script_path, user):
352
 
    """Gets CGI variables from apache and makes a few changes for security and 
353
 
    correctness.
354
 
 
355
 
    Does not modify req, only reads it.
356
 
    """
357
 
    env = {}
358
 
    # Comments here are on the heavy side, explained carefully for security
359
 
    # reasons. Please read carefully before making changes.
360
 
    
361
 
    # This automatically asks mod_python to load up the CGI variables into the
362
 
    # environment (which is a good first approximation)
363
 
    for (k,v) in req.get_cgi_environ().items():
364
 
        env[k] = v
365
 
 
366
 
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
367
 
    # exposes unnecessary details about server.
368
 
    try:
369
 
        del env['DOCUMENT_ROOT']
370
 
    except: pass
371
 
    try:
372
 
        del env['SCRIPT_FILENAME']
373
 
    except: pass
374
 
 
375
 
    # Remove PATH. The PATH here is the path on the server machine; not useful
376
 
    # inside the jail. It may be a good idea to add another path, reflecting
377
 
    # the inside of the jail, but not done at this stage.
378
 
    try:
379
 
        del env['PATH']
380
 
    except: pass
381
 
 
382
 
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
383
 
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
384
 
    # REMOTE_ADDR.
385
 
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
386
 
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
387
 
 
388
 
    env['PATH_INFO'] = ''
389
 
    del env['PATH_TRANSLATED']
390
 
 
391
 
    normuri = os.path.normpath(req.uri)
392
 
    env['SCRIPT_NAME'] = normuri
393
 
 
394
 
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
395
 
    # We don't care about these if the script is null (ie. noop).
396
 
    # XXX: We check for /home because we don't want to interfere with
397
 
    # CGIRequest, which fileservice still uses.
398
 
    if script_path and script_path.startswith('/home'):
399
 
        normscript = os.path.normpath(script_path)
400
 
 
401
 
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
402
 
 
403
 
        # PATH_INFO is wrong because the script doesn't physically exist.
404
 
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
405
 
        if len(env['PATH_INFO']) > 0:
406
 
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
407
 
 
408
 
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
409
 
    # custom-making the CGI request.
410
 
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
411
 
 
412
 
    # Additional environment variables
413
 
    username = user.login
414
 
    env['HOME'] = os.path.join('/home', username)
415
 
 
416
 
    return env
417
 
 
418
 
class ExecutionError(Exception):
419
 
    pass
420
 
 
421
 
def execute_raw(config, user, jail_dir, working_dir, binary, args):
422
 
    '''Execute a binary in a user's jail, returning the raw output.
423
 
 
424
 
    The binary is executed in the given working directory with the given
425
 
    args. A tuple of (stdout, stderr) is returned.
426
 
    '''
427
 
 
428
 
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
429
 
    tramp_dir = os.path.split(tramp)[0]
430
 
 
431
 
    # Fire up trampoline. Vroom, vroom.
432
 
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
433
 
         config['paths']['jails']['src'],
434
 
         config['paths']['jails']['template'],
435
 
         jail_dir, working_dir, binary] + args
436
 
    # Popen doesn't like unicode strings. It hateses them.
437
 
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
438
 
                for s in cmd_line]
439
 
    proc = subprocess.Popen(cmd_line,
440
 
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
441
 
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
442
 
        env={'HOME': os.path.join('/home', user.login),
443
 
             'PATH': PATH,
444
 
             'USER': user.login,
445
 
             'LOGNAME': user.login})
446
 
 
447
 
    (stdout, stderr) = proc.communicate()
448
 
    exitcode = proc.returncode
449
 
 
450
 
    if exitcode != 0:
451
 
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
452
 
                             (exitcode, stderr))
453
 
    return (stdout, stderr)