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

1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
24
import ivle
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
25
from ivle import studpath
1270 by William Grant
Rename to to_home_path, and use it in ivle.interpret.
26
from ivle.util import IVLEError, IVLEJailError, split_path
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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.
1080.1.66 by William Grant
ivle.interpret.interpret_file: Take a User object as the owner, not a login.
48
    owner: The user who owns the file being served.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1080.1.66 by William Grant
ivle.interpret.interpret_file: Take a User object as the owner, not a login.
76
    return interpreter(owner.unixid, jail_dir, working_dir, filename_abs, req,
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
91
def execute_cgi(interpreter, uid, jail_dir, working_dir, script_path,
92
                req, gentle):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
108
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
109
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
110
    # Support no-op trampoline runs.
111
    if interpreter is None:
112
        interpreter = '/bin/true'
113
        script_path = ''
114
        noop = True
115
    else:
116
        noop = False
117
118
    # Get the student program's directory and execute it from that context.
119
    (tramp_dir, _) = os.path.split(trampoline)
120
121
    # TODO: Don't create a file if the body length is known to be 0
122
    # Write the HTTP body to a temporary file so it can be passed as a *real*
123
    # file to popen.
124
    f = os.tmpfile()
125
    body = req.read() if not noop else None
126
    if body is not None:
127
        f.write(body)
128
        f.flush()
129
        f.seek(0)       # Rewind, for reading
130
131
    # Set up the environment
132
    # This automatically asks mod_python to load up the CGI variables into the
133
    # environment (which is a good first approximation)
134
    old_env = os.environ.copy()
135
    for k in os.environ.keys():
136
        del os.environ[k]
137
    for (k,v) in req.get_cgi_environ().items():
138
        os.environ[k] = v
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
139
    fixup_environ(req, script_path)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
140
141
    # usage: tramp uid jail_dir working_dir script_path
142
    pid = subprocess.Popen(
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
143
        [trampoline, str(uid), req.config['paths']['jails']['mounts'],
144
         req.config['paths']['jails']['src'],
145
         req.config['paths']['jails']['template'],
146
         jail_dir, working_dir, interpreter, script_path],
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
147
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
148
        cwd=tramp_dir)
149
150
    # Restore the environment
151
    for k in os.environ.keys():
152
        del os.environ[k]
153
    for (k,v) in old_env.items():
154
        os.environ[k] = v
155
156
    # We don't want any output! Bail out after the process terminates.
157
    if noop:
158
        pid.communicate()
159
        return
160
161
    # process_cgi_line: Reads a single line of CGI output and processes it.
162
    # Prints to req, and also does fancy HTML warnings if Content-Type
163
    # omitted.
164
    cgiflags = CGIFlags(gentle)
165
166
    # Read from the process's stdout into req
167
    data = pid.stdout.read(CGI_BLOCK_SIZE)
168
    while len(data) > 0:
169
        process_cgi_output(req, data, cgiflags)
170
        data = pid.stdout.read(CGI_BLOCK_SIZE)
171
172
    # If we haven't processed headers yet, now is a good time
173
    if not cgiflags.started_cgi_body:
174
        process_cgi_output(req, '\n', cgiflags)
175
176
    # If we wrote an HTML warning header, write the footer
177
    if cgiflags.wrote_html_warning:
178
        req.write("""</pre>
179
  </div>
180
</body>
181
</html>""")
182
183
def process_cgi_output(req, data, cgiflags):
184
    """Processes a chunk of CGI output. data is a string of arbitrary length;
185
    some arbitrary chunk of output written by the CGI script."""
186
    if cgiflags.started_cgi_body:
187
        if cgiflags.wrote_html_warning:
188
            # HTML escape text if wrote_html_warning
189
            req.write(cgi.escape(data))
190
        else:
191
            req.write(data)
192
    else:
193
        # Break data into lines of CGI header data. 
194
        linebuf = cgiflags.linebuf + data
195
        # First see if we can split all header data
196
        # We need to get the double CRLF- or LF-terminated headers, whichever
197
        # is smaller, as either sequence may appear somewhere in the body.
198
        usplit = linebuf.split('\n\n', 1)
199
        wsplit = linebuf.split('\r\n\r\n', 1)
200
        split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
201
        if len(split) == 1:
202
            # Haven't seen all headers yet. Buffer and come back later.
203
            cgiflags.linebuf = linebuf
204
            return
205
206
        headers = split[0]
207
        data = split[1]
208
        cgiflags.linebuf = ""
209
        cgiflags.started_cgi_body = True
210
        # Process all the header lines
211
        split = headers.split('\r\n', 1)
212
        if len(split) == 1:
213
            split = headers.split('\n', 1)
214
        while True:
215
            process_cgi_header_line(req, split[0], cgiflags)
216
            if len(split) == 1: break
217
            headers = split[1]
218
            if cgiflags.wrote_html_warning:
219
                # We're done with headers. Treat the rest as data.
220
                data = headers + '\n' + data
221
                break
222
            split = headers.split('\r\n', 1)
223
            if len(split) == 1:
224
                split = headers.split('\n', 1)
225
226
        # Is this an internal IVLE error condition?
227
        hs = cgiflags.headers
228
        if 'X-IVLE-Error-Type' in hs:
229
            t = hs['X-IVLE-Error-Type']
230
            if t == IVLEError.__name__:
231
                raise IVLEError(int(hs['X-IVLE-Error-Code']),
232
                                hs['X-IVLE-Error-Message'])
233
            else:
234
                try:
235
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
236
                                        hs['X-IVLE-Error-Message'],
237
                                        hs['X-IVLE-Error-Info'])
238
                except KeyError:
239
                    raise IVLEError(500, 'bad error headers written by CGI')
240
241
        # Check to make sure the required headers were written
242
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
243
            # We already reported an error, that's enough
244
            pass
245
        elif "Content-Type" in cgiflags.headers:
246
            pass
247
        elif "Location" in cgiflags.headers:
248
            if ("Status" in cgiflags.headers and req.status >= 300
249
                and req.status < 400):
250
                pass
251
            else:
252
                message = """You did not write a valid status code for
253
the given location. To make a redirect, you may wish to try:</p>
254
<pre style="margin-left: 1em">Status: 302 Found
255
Location: &lt;redirect address&gt;</pre>"""
256
                write_html_warning(req, message)
257
                cgiflags.wrote_html_warning = True
258
        else:
259
            message = """You did not print a Content-Type header.
260
CGI requires that you print a "Content-Type". You may wish to try:</p>
261
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
262
            write_html_warning(req, message)
263
            cgiflags.wrote_html_warning = True
264
265
        # Call myself to flush out the extra bit of data we read
266
        process_cgi_output(req, data, cgiflags)
267
268
def process_cgi_header_line(req, line, cgiflags):
269
    """Process a line of CGI header data. line is a string representing a
270
    complete line of text, stripped and without the newline.
271
    """
272
    try:
273
        name, value = line.split(':', 1)
274
    except ValueError:
275
        # No colon. The user did not write valid headers.
276
        # If we are being gentle, we want to help the user understand what
277
        # went wrong. Otherwise, just admit we screwed up.
278
        warning = "Warning"
279
        if not cgiflags.gentle:
280
            message = """An unexpected server error has occured."""
281
            warning = "Error"
282
        elif len(cgiflags.headers) == 0:
283
            # First line was not a header line. We can assume this is not
284
            # a CGI app.
285
            message = """You did not print a CGI header.
286
CGI requires that you print a "Content-Type". You may wish to try:</p>
287
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
288
        else:
289
            # They printed some header at least, but there was an invalid
290
            # header.
291
            message = """You printed an invalid CGI header. You need to leave
292
a blank line after the headers, before writing the page contents."""
293
        write_html_warning(req, message, warning=warning)
294
        cgiflags.wrote_html_warning = True
295
        # Handle the rest of this line as normal data
296
        process_cgi_output(req, line + '\n', cgiflags)
297
        return
298
299
    # Read CGI headers
300
    value = value.strip()
301
    if name == "Content-Type":
302
        req.content_type = value
303
    elif name == "Location":
304
        req.location = value
305
    elif name == "Status":
306
        # Must be an integer, followed by a space, and then the status line
307
        # which we ignore (seems like Apache has no way to send a custom
308
        # status line).
309
        try:
310
            req.status = int(value.split(' ', 1)[0])
311
        except ValueError:
312
            if not cgiflags.gentle:
313
                # This isn't user code, so it should be good.
314
                # Get us out of here!
315
                raise
316
            message = """The "Status" CGI header was invalid. You need to
317
print a number followed by a message, such as "302 Found"."""
318
            write_html_warning(req, message)
319
            cgiflags.wrote_html_warning = True
320
            # Handle the rest of this line as normal data
321
            process_cgi_output(req, line + '\n', cgiflags)
322
    else:
323
        # Generic HTTP header
324
        # FIXME: Security risk letting users write arbitrary headers?
325
        req.headers_out.add(name, value)
326
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
327
328
def write_html_warning(req, text, warning="Warning"):
329
    """Prints an HTML warning about invalid CGI interaction on the part of the
330
    user. text may contain HTML markup."""
331
    req.content_type = "text/html"
332
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
333
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
334
<html xmlns="http://www.w3.org/1999/xhtml">
335
<head>
336
  <meta http-equiv="Content-Type"
337
    content="text/html; charset=utf-8" />
338
</head>
339
<body style="margin: 0; padding: 0; font-family: sans-serif;">
340
  <div style="background-color: #faa; border-bottom: 1px solid black;
341
    padding: 8px;">
342
    <p><strong>%s</strong>: %s
343
  </div>
344
  <div style="margin: 8px;">
345
    <pre>
346
""" % (warning, text))
347
348
# Mapping of interpreter names (as given in conf/app/server.py) to
349
# interpreter functions.
350
351
interpreter_objects = {
352
    'cgi-python'
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
353
        : functools.partial(execute_cgi, "/usr/bin/python"),
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
354
    'noop'
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
355
        : functools.partial(execute_cgi, None),
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
356
    # Should also have:
357
    # cgi-generic
358
    # python-server-page
359
}
360
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
361
def fixup_environ(req, script_path):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
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
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
388
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
389
    # REMOTE_ADDR.
390
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
391
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
392
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
393
    env['PATH_INFO'] = ''
394
    del env['PATH_TRANSLATED']
395
396
    normuri = os.path.normpath(req.uri)
397
    env['SCRIPT_NAME'] = normuri
398
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
399
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
400
    # We don't care about these if the script is null (ie. noop).
401
    # XXX: We check for /home because we don't want to interfere with
402
    # CGIRequest, which fileservice still uses.
403
    if script_path and script_path.startswith('/home'):
404
        normscript = os.path.normpath(script_path)
405
1270 by William Grant
Rename to to_home_path, and use it in ivle.interpret.
406
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
407
408
        # PATH_INFO is wrong because the script doesn't physically exist.
409
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
410
        if len(env['PATH_INFO']) > 0:
411
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
412
413
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
414
    # custom-making the CGI request.
1274 by William Grant
Move ivle.conf.ivle_version to ivle.__version__.
415
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
416
417
    # Additional environment variables
1270 by William Grant
Rename to to_home_path, and use it in ivle.interpret.
418
    username = split_path(req.path)[0]
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
419
    env['HOME'] = os.path.join('/home', username)
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
420
421
class ExecutionError(Exception):
422
    pass
423
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
424
def execute_raw(config, user, jail_dir, working_dir, binary, args):
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
425
    '''Execute a binary in a user's jail, returning the raw output.
426
427
    The binary is executed in the given working directory with the given
428
    args. A tuple of (stdout, stderr) is returned.
429
    '''
430
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
431
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
432
    tramp_dir = os.path.split(tramp)[0]
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
433
434
    # Fire up trampoline. Vroom, vroom.
435
    proc = subprocess.Popen(
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
436
        [tramp, str(user.unixid), config['paths']['jails']['mounts'],
437
         config['paths']['jails']['src'],
438
         config['paths']['jails']['template'],
439
         jail_dir, working_dir, binary] + args,
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
440
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
441
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
1164 by William Grant
ivle.interpret.execute_raw() no longer breaks with lots of data.
442
443
    (stdout, stderr) = proc.communicate()
444
    exitcode = proc.returncode
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
445
446
    if exitcode != 0:
447
        raise ExecutionError('subprocess ended with code %d, stderr %s' %
448
                             (exitcode, proc.stderr.read()))
1164 by William Grant
ivle.interpret.execute_raw() no longer breaks with lots of data.
449
    return (stdout, stderr)