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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: Matt Giuca
  • Date: 2010-02-25 08:36:59 UTC
  • Revision ID: matt.giuca@gmail.com-20100225083659-2s8vdrfhx3bhvcmp
DateTimeValidator: Removed some debugging code. Oops.

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 import db
26
 
from ivle.util import IVLEError, IVLEJailError
27
 
import ivle.conf
 
26
from ivle.util import IVLEError, IVLEJailError, split_path
28
27
 
29
28
import functools
30
29
 
39
38
 
40
39
CGI_BLOCK_SIZE = 65535
41
40
 
42
 
uids = {}
43
 
 
44
 
def get_uid(login):
45
 
    """Get the unix uid corresponding to the given login name.
46
 
       If it is not in the dictionary of uids, then consult the
47
 
       database and retrieve an update of the user table."""
48
 
    global uids
49
 
    if login in uids:
50
 
        return uids[login]
51
 
 
52
 
    conn = db.DB()
53
 
    res = conn.get_all('login', ['login', 'unixid'])
54
 
    def repack(flds):
55
 
        return (flds['login'], flds['unixid'])
56
 
    uids = dict(map(repack,res))
57
 
 
58
 
    return uids[login]
59
 
 
60
41
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
61
42
    """Serves a file by interpreting it using one of IVLE's builtin
62
43
    interpreters. All interpreters are intended to run in the user's jail. The
64
45
    to the individual interpreters to create the jail.
65
46
 
66
47
    req: An IVLE request object.
67
 
    owner: Username of the user who owns the file being served.
 
48
    owner: The user who owns the file being served.
68
49
    jail_dir: Absolute path to the user's jail.
69
50
    filename: Absolute filename within the user's jail.
70
51
    interpreter: A function object to call.
79
60
        filename_abs = os.path.join(os.sep, filename)
80
61
        filename_rel = filename
81
62
 
82
 
    # Get the UID of the owner of the file
83
63
    # (Note: files are executed by their owners, not the logged in user.
84
64
    # This ensures users are responsible for their own programs and also
85
65
    # allows them to be executed by the public).
86
 
    uid = get_uid(owner)
87
66
 
88
67
    # Split up req.path again, this time with respect to the jail
89
68
    (working_dir, _) = os.path.split(filename_abs)
94
73
    # (Note that paths "relative" to the jail actually begin with a '/' as
95
74
    # they are absolute in the jailspace)
96
75
 
97
 
    return interpreter(uid, jail_dir, working_dir, filename_abs, req,
 
76
    return interpreter(owner.unixid, jail_dir, working_dir, filename_abs, req,
98
77
                       gentle)
99
78
 
100
79
class CGIFlags:
109
88
        self.linebuf = ""
110
89
        self.headers = {}       # Header names : values
111
90
 
112
 
def execute_cgi(interpreter, trampoline, uid, jail_dir, working_dir,
113
 
                script_path, req, gentle):
 
91
def execute_cgi(interpreter, uid, jail_dir, working_dir, script_path,
 
92
                req, gentle):
114
93
    """
115
94
    trampoline: Full path on the local system to the CGI wrapper program
116
95
        being executed.
126
105
    its environment.
127
106
    """
128
107
 
 
108
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
 
109
 
129
110
    # Support no-op trampoline runs.
130
111
    if interpreter is None:
131
112
        interpreter = '/bin/true'
155
136
        del os.environ[k]
156
137
    for (k,v) in req.get_cgi_environ().items():
157
138
        os.environ[k] = v
158
 
    fixup_environ(req)
 
139
    fixup_environ(req, script_path)
159
140
 
160
141
    # usage: tramp uid jail_dir working_dir script_path
161
 
    pid = subprocess.Popen(
162
 
        [trampoline, str(uid), jail_dir, working_dir, interpreter,
163
 
        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,
164
150
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
165
151
        cwd=tramp_dir)
166
152
 
362
348
    <pre>
363
349
""" % (warning, text))
364
350
 
365
 
location_cgi_python = os.path.join(ivle.conf.lib_path, "trampoline")
366
 
 
367
351
# Mapping of interpreter names (as given in conf/app/server.py) to
368
352
# interpreter functions.
369
353
 
370
354
interpreter_objects = {
371
355
    'cgi-python'
372
 
        : functools.partial(execute_cgi, "/usr/bin/python",
373
 
            location_cgi_python),
 
356
        : functools.partial(execute_cgi, "/usr/bin/python"),
374
357
    'noop'
375
 
        : functools.partial(execute_cgi, None,
376
 
            location_cgi_python),
 
358
        : functools.partial(execute_cgi, None),
377
359
    # Should also have:
378
360
    # cgi-generic
379
361
    # python-server-page
380
362
}
381
363
 
382
 
def fixup_environ(req):
 
364
def fixup_environ(req, script_path):
383
365
    """Assuming os.environ has been written with the CGI variables from
384
366
    apache, make a few changes for security and correctness.
385
367
 
405
387
        del env['PATH']
406
388
    except: pass
407
389
 
408
 
    # Remove SCRIPT_FILENAME. Not part of CGI spec (see SCRIPT_NAME).
409
 
 
410
 
    # PATH_INFO is wrong because the script doesn't physically exist.
411
 
    # Apache makes it relative to the "serve" app. It should actually be made
412
 
    # relative to the student's script. intepretservice does that in the jail,
413
 
    # so here we just clear it.
414
 
    env['PATH_INFO'] = ''
415
 
    env['PATH_TRANSLATED'] = ''
416
 
 
417
390
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
418
391
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
419
392
    # REMOTE_ADDR.
420
393
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
421
394
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
422
395
 
 
396
    env['PATH_INFO'] = ''
 
397
    del env['PATH_TRANSLATED']
 
398
 
 
399
    normuri = os.path.normpath(req.uri)
 
400
    env['SCRIPT_NAME'] = normuri
 
401
 
423
402
    # SCRIPT_NAME is the path to the script WITHOUT PATH_INFO.
424
 
    script_name = req.uri
425
 
    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'])]
426
415
 
427
416
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
428
417
    # custom-making the CGI request.
429
 
    env['SERVER_SOFTWARE'] = "IVLE/" + str(ivle.conf.ivle_version)
 
418
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
430
419
 
431
420
    # Additional environment variables
432
 
    username = studpath.url_to_jailpaths(req.path)[0]
 
421
    username = split_path(req.path)[0]
433
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)