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

« back to all changes in this revision

Viewing changes to ivle/interpret.py

  • Committer: William Grant
  • Date: 2010-03-03 04:05:17 UTC
  • Revision ID: grantw@unimelb.edu.au-20100303040517-7grsyhj96ksqzi9e
Remove IVLEError support; only fileservice used it, and the last invocation is GONE.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
 
24
24
import ivle
25
25
from ivle import studpath
26
 
from ivle.util import IVLEError, IVLEJailError, split_path
 
26
from ivle.util import IVLEJailError, split_path
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"
40
41
 
41
42
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True):
42
43
    """Serves a file by interpreting it using one of IVLE's builtin
73
74
    # (Note that paths "relative" to the jail actually begin with a '/' as
74
75
    # they are absolute in the jailspace)
75
76
 
76
 
    return interpreter(owner.unixid, jail_dir, working_dir, filename_abs, req,
 
77
    return interpreter(owner, jail_dir, working_dir, filename_abs, req,
77
78
                       gentle)
78
79
 
79
80
class CGIFlags:
88
89
        self.linebuf = ""
89
90
        self.headers = {}       # Header names : values
90
91
 
91
 
def execute_cgi(interpreter, uid, jail_dir, working_dir, script_path,
 
92
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
92
93
                req, gentle):
93
94
    """
94
95
    trampoline: Full path on the local system to the CGI wrapper program
95
96
        being executed.
96
 
    uid: User ID of the owner of the file.
 
97
    owner: User object of the owner of the file.
97
98
    jail_dir: Absolute path of owner's jail directory.
98
99
    working_dir: Directory containing the script file relative to owner's
99
100
        jail.
129
130
        f.seek(0)       # Rewind, for reading
130
131
 
131
132
    # 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
139
 
    fixup_environ(req, script_path)
 
133
    environ = cgi_environ(req, script_path, owner)
140
134
 
141
135
    # usage: tramp uid jail_dir working_dir script_path
142
 
    pid = subprocess.Popen(
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],
 
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,
147
145
        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
 
146
        cwd=tramp_dir, env=environ)
155
147
 
156
148
    # We don't want any output! Bail out after the process terminates.
157
149
    if noop:
226
218
        # Is this an internal IVLE error condition?
227
219
        hs = cgiflags.headers
228
220
        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')
 
221
            try:
 
222
                raise IVLEJailError(hs['X-IVLE-Error-Type'],
 
223
                                    hs['X-IVLE-Error-Message'],
 
224
                                    hs['X-IVLE-Error-Info'])
 
225
            except KeyError:
 
226
                raise AssertionError("Bad error headers written by CGI.")
240
227
 
241
228
        # Check to make sure the required headers were written
242
229
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
358
345
    # python-server-page
359
346
}
360
347
 
361
 
def fixup_environ(req, script_path):
362
 
    """Assuming os.environ has been written with the CGI variables from
363
 
    apache, make a few changes for security and correctness.
 
348
def cgi_environ(req, script_path, user):
 
349
    """Gets CGI variables from apache and makes a few changes for security and 
 
350
    correctness.
364
351
 
365
352
    Does not modify req, only reads it.
366
353
    """
367
 
    env = os.environ
 
354
    env = {}
368
355
    # Comments here are on the heavy side, explained carefully for security
369
356
    # reasons. Please read carefully before making changes.
 
357
    
 
358
    # This automatically asks mod_python to load up the CGI variables into the
 
359
    # environment (which is a good first approximation)
 
360
    for (k,v) in req.get_cgi_environ().items():
 
361
        env[k] = v
370
362
 
371
363
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
372
364
    # exposes unnecessary details about server.
415
407
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
416
408
 
417
409
    # Additional environment variables
418
 
    username = split_path(req.path)[0]
 
410
    username = user.login
419
411
    env['HOME'] = os.path.join('/home', username)
420
412
 
 
413
    return env
 
414
 
421
415
class ExecutionError(Exception):
422
416
    pass
423
417
 
432
426
    tramp_dir = os.path.split(tramp)[0]
433
427
 
434
428
    # Fire up trampoline. Vroom, vroom.
435
 
    proc = subprocess.Popen(
436
 
        [tramp, str(user.unixid), config['paths']['jails']['mounts'],
 
429
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
437
430
         config['paths']['jails']['src'],
438
431
         config['paths']['jails']['template'],
439
 
         jail_dir, working_dir, binary] + args,
 
432
         jail_dir, working_dir, binary] + args
 
433
    # Popen doesn't like unicode strings. It hateses them.
 
434
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
 
435
                for s in cmd_line]
 
436
    proc = subprocess.Popen(cmd_line,
440
437
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
441
 
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True)
 
438
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
 
439
        env={'HOME': os.path.join('/home', user.login),
 
440
             'PATH': PATH,
 
441
             'USER': user.login,
 
442
             'LOGNAME': user.login})
442
443
 
443
444
    (stdout, stderr) = proc.communicate()
444
445
    exitcode = proc.returncode
445
446
 
446
447
    if exitcode != 0:
447
 
        raise ExecutionError('subprocess ended with code %d, stderr %s' %
448
 
                             (exitcode, proc.stderr.read()))
 
448
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
 
449
                             (exitcode, stderr))
449
450
    return (stdout, stderr)