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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

Quick port of fileservice to the new framework. It's still very much old-style,
though.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
# Runs a student script in a safe execution environment.
23
23
 
24
 
import ivle
25
24
from ivle import studpath
26
 
from ivle.util import IVLEJailError, split_path
 
25
from ivle.util import IVLEError, IVLEJailError
 
26
import ivle.conf
27
27
 
28
28
import functools
29
29
 
37
37
# working on smaller output
38
38
 
39
39
CGI_BLOCK_SIZE = 65535
40
 
PATH = "/usr/local/bin:/usr/bin:/bin"
41
40
 
42
41
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
43
42
    """Serves a file by interpreting it using one of IVLE's builtin
74
73
    # (Note that paths "relative" to the jail actually begin with a '/' as
75
74
    # they are absolute in the jailspace)
76
75
 
77
 
    return interpreter(owner, jail_dir, working_dir, filename_abs, req,
 
76
    return interpreter(owner.unixid, jail_dir, working_dir, filename_abs, req,
78
77
                       gentle)
79
78
 
80
79
class CGIFlags:
89
88
        self.linebuf = ""
90
89
        self.headers = {}       # Header names : values
91
90
 
92
 
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
93
 
                req, gentle):
 
91
def execute_cgi(interpreter, trampoline, uid, jail_dir, working_dir,
 
92
                script_path, req, gentle):
94
93
    """
95
94
    trampoline: Full path on the local system to the CGI wrapper program
96
95
        being executed.
97
 
    owner: User object of the owner of the file.
 
96
    uid: User ID of the owner of the file.
98
97
    jail_dir: Absolute path of owner's jail directory.
99
98
    working_dir: Directory containing the script file relative to owner's
100
99
        jail.
106
105
    its environment.
107
106
    """
108
107
 
109
 
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
110
 
 
111
108
    # Support no-op trampoline runs.
112
109
    if interpreter is None:
113
110
        interpreter = '/bin/true'
130
127
        f.seek(0)       # Rewind, for reading
131
128
 
132
129
    # Set up the environment
133
 
    environ = cgi_environ(req, script_path, owner)
 
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)
134
138
 
135
139
    # 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,
 
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],
145
144
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
146
 
        cwd=tramp_dir, env=environ)
 
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
147
152
 
148
153
    # We don't want any output! Bail out after the process terminates.
149
154
    if noop:
215
220
            if len(split) == 1:
216
221
                split = headers.split('\n', 1)
217
222
 
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:
 
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:
224
231
                try:
225
232
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
226
233
                                        hs['X-IVLE-Error-Message'],
227
234
                                        hs['X-IVLE-Error-Info'])
228
235
                except KeyError:
229
 
                    raise AssertionError("Bad error headers written by CGI.")
 
236
                    raise IVLEError(500, 'bad error headers written by CGI')
230
237
 
231
238
        # Check to make sure the required headers were written
232
239
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
335
342
    <pre>
336
343
""" % (warning, text))
337
344
 
 
345
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
 
346
 
338
347
# Mapping of interpreter names (as given in conf/app/server.py) to
339
348
# interpreter functions.
340
349
 
341
350
interpreter_objects = {
342
351
    'cgi-python'
343
 
        : functools.partial(execute_cgi, "/usr/bin/python"),
 
352
        : functools.partial(execute_cgi, "/usr/bin/python",
 
353
            location_cgi_python),
344
354
    'noop'
345
 
        : functools.partial(execute_cgi, None),
 
355
        : functools.partial(execute_cgi, None,
 
356
            location_cgi_python),
346
357
    # Should also have:
347
358
    # cgi-generic
348
359
    # python-server-page
349
360
}
350
361
 
351
 
def cgi_environ(req, script_path, user):
352
 
    """Gets CGI variables from apache and makes a few changes for security and 
353
 
    correctness.
 
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.
354
365
 
355
366
    Does not modify req, only reads it.
356
367
    """
357
 
    env = {}
 
368
    env = os.environ
358
369
    # Comments here are on the heavy side, explained carefully for security
359
370
    # 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
371
 
366
372
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
367
373
    # exposes unnecessary details about server.
398
404
    if script_path and script_path.startswith('/home'):
399
405
        normscript = os.path.normpath(script_path)
400
406
 
401
 
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
 
407
        uri_into_jail = studpath.url_to_jailpaths(os.path.normpath(req.path))[2]
402
408
 
403
409
        # PATH_INFO is wrong because the script doesn't physically exist.
404
410
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
407
413
 
408
414
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
409
415
    # custom-making the CGI request.
410
 
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
 
416
    env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
411
417
 
412
418
    # Additional environment variables
413
 
    username = user.login
 
419
    username = studpath.url_to_jailpaths(req.path)[0]
414
420
    env['HOME'] = os.path.join('/home', username)
415
421
 
416
 
    return env
417
 
 
418
422
class ExecutionError(Exception):
419
423
    pass
420
424
 
421
 
def execute_raw(config, user, jail_dir, working_dir, binary, args):
 
425
def execute_raw(user, jail_dir, working_dir, binary, args):
422
426
    '''Execute a binary in a user's jail, returning the raw output.
423
427
 
424
428
    The binary is executed in the given working directory with the given
425
429
    args. A tuple of (stdout, stderr) is returned.
426
430
    '''
427
431
 
428
 
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
429
 
    tramp_dir = os.path.split(tramp)[0]
 
432
    tramp = location_cgi_python
 
433
    tramp_dir = os.path.split(location_cgi_python)[0]
430
434
 
431
435
    # 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,
 
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
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
 
441
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
 
442
    exitcode = proc.wait()
449
443
 
450
444
    if exitcode != 0:
451
 
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
452
 
                             (exitcode, stderr))
453
 
    return (stdout, stderr)
 
445
        raise ExecutionError('subprocess ended with code %d, stderr %s' %
 
446
                             (exitcode, proc.stderr.read()))
 
447
    return (proc.stdout.read(), proc.stderr.read())