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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: William Grant
  • Date: 2010-02-25 09:36:51 UTC
  • Revision ID: grantw@unimelb.edu.au-20100225093651-mj6pdjw8idyacptr
Start a console backend immediately in ConsoleView, and when the overlay is maximised.

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
24
25
from ivle import studpath
25
 
from ivle.util import IVLEError, IVLEJailError
26
 
import ivle.conf
 
26
from ivle.util import IVLEError, IVLEJailError, split_path
27
27
 
28
28
import functools
29
29
 
88
88
        self.linebuf = ""
89
89
        self.headers = {}       # Header names : values
90
90
 
91
 
def execute_cgi(interpreter, trampoline, uid, jail_dir, working_dir,
92
 
                script_path, req, gentle):
 
91
def execute_cgi(interpreter, uid, jail_dir, working_dir, script_path,
 
92
                req, gentle):
93
93
    """
94
94
    trampoline: Full path on the local system to the CGI wrapper program
95
95
        being executed.
105
105
    its environment.
106
106
    """
107
107
 
 
108
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
 
109
 
108
110
    # Support no-op trampoline runs.
109
111
    if interpreter is None:
110
112
        interpreter = '/bin/true'
134
136
        del os.environ[k]
135
137
    for (k,v) in req.get_cgi_environ().items():
136
138
        os.environ[k] = v
137
 
    fixup_environ(req)
 
139
    fixup_environ(req, script_path)
138
140
 
139
141
    # 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],
 
142
    cmd_line = [trampoline, str(uid), req.config['paths']['jails']['mounts'],
 
143
         req.config['paths']['jails']['src'],
 
144
         req.config['paths']['jails']['template'],
 
145
         jail_dir, working_dir, interpreter, script_path]
 
146
    # Popen doesn't like unicode strings. It hateses them.
 
147
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
 
148
                for s in cmd_line]
 
149
    pid = subprocess.Popen(cmd_line,
143
150
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
144
151
        cwd=tramp_dir)
145
152
 
341
348
    <pre>
342
349
""" % (warning, text))
343
350
 
344
 
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
345
 
 
346
351
# Mapping of interpreter names (as given in conf/app/server.py) to
347
352
# interpreter functions.
348
353
 
349
354
interpreter_objects = {
350
355
    'cgi-python'
351
 
        : functools.partial(execute_cgi, "/usr/bin/python",
352
 
            location_cgi_python),
 
356
        : functools.partial(execute_cgi, "/usr/bin/python"),
353
357
    'noop'
354
 
        : functools.partial(execute_cgi, None,
355
 
            location_cgi_python),
 
358
        : functools.partial(execute_cgi, None),
356
359
    # Should also have:
357
360
    # cgi-generic
358
361
    # python-server-page
359
362
}
360
363
 
361
 
def fixup_environ(req):
 
364
def fixup_environ(req, script_path):
362
365
    """Assuming os.environ has been written with the CGI variables from
363
366
    apache, make a few changes for security and correctness.
364
367
 
384
387
        del env['PATH']
385
388
    except: pass
386
389
 
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
390
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
397
391
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
398
392
    # REMOTE_ADDR.
399
393
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
400
394
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
401
395
 
 
396
    env['PATH_INFO'] = ''
 
397
    del env['PATH_TRANSLATED']
 
398
 
 
399
    normuri = os.path.normpath(req.uri)
 
400
    env['SCRIPT_NAME'] = normuri
 
401
 
402
402
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
403
 
    script_name = req.uri
404
 
    env['SCRIPT_NAME'] = script_name
 
403
    # We don't care about these if the script is null (ie. noop).
 
404
    # XXX: We check for /home because we don't want to interfere with
 
405
    # CGIRequest, which fileservice still uses.
 
406
    if script_path and script_path.startswith('/home'):
 
407
        normscript = os.path.normpath(script_path)
 
408
 
 
409
        uri_into_jail = studpath.to_home_path(os.path.normpath(req.path))
 
410
 
 
411
        # PATH_INFO is wrong because the script doesn't physically exist.
 
412
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
 
413
        if len(env['PATH_INFO']) > 0:
 
414
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
405
415
 
406
416
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
407
417
    # custom-making the CGI request.
408
 
    env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
 
418
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
409
419
 
410
420
    # Additional environment variables
411
 
    username = studpath.url_to_jailpaths(req.path)[0]
 
421
    username = split_path(req.path)[0]
412
422
    env['HOME'] = os.path.join('/home', username)
 
423
 
 
424
class ExecutionError(Exception):
 
425
    pass
 
426
 
 
427
def execute_raw(config, user, jail_dir, working_dir, binary, args):
 
428
    '''Execute a binary in a user's jail, returning the raw output.
 
429
 
 
430
    The binary is executed in the given working directory with the given
 
431
    args. A tuple of (stdout, stderr) is returned.
 
432
    '''
 
433
 
 
434
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
 
435
    tramp_dir = os.path.split(tramp)[0]
 
436
 
 
437
    # Fire up trampoline. Vroom, vroom.
 
438
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
 
439
         config['paths']['jails']['src'],
 
440
         config['paths']['jails']['template'],
 
441
         jail_dir, working_dir, binary] + args
 
442
    # Popen doesn't like unicode strings. It hateses them.
 
443
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
 
444
                for s in cmd_line]
 
445
    proc = subprocess.Popen(cmd_line,
 
446
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 
447
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
 
448
 
 
449
    (stdout, stderr) = proc.communicate()
 
450
    exitcode = proc.returncode
 
451
 
 
452
    if exitcode != 0:
 
453
        raise ExecutionError('subprocess ended with code %d, stderr %s' %
 
454
                             (exitcode, proc.stderr.read()))
 
455
    return (stdout, stderr)