~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
1779 by William Grant
Remove IVLEError support; only fileservice used it, and the last invocation is GONE.
26
from ivle.util import 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
1776 by David Coles
interpret: Hard code PATH for interpret_raw since it's not always set correctly in Apache threads
40
PATH = "/usr/local/bin:/usr/bin:/bin"
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
41
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
42
def interpret_file(req, owner, jail_dir, filename, interpreter, gentle=True,
43
    overrides=None):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
44
    """Serves a file by interpreting it using one of IVLE's builtin
45
    interpreters. All interpreters are intended to run in the user's jail. The
46
    jail location is provided as an argument to the interpreter but it is up
47
    to the individual interpreters to create the jail.
48
49
    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.
50
    owner: The user who owns the file being served.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
51
    jail_dir: Absolute path to the user's jail.
52
    filename: Absolute filename within the user's jail.
53
    interpreter: A function object to call.
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
54
    gentle: ?
55
    overrides: A dict mapping env var names to strings, to override arbitrary
56
        environment variables in the resulting CGI environent.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
57
    """
58
    # We can't test here whether or not the target file actually exists,
59
    # because the apache user may not have permission. Instead we have to
60
    # rely on the interpreter generating an error.
61
    if filename.startswith(os.sep):
62
        filename_abs = filename
63
        filename_rel = filename[1:]
64
    else:
65
        filename_abs = os.path.join(os.sep, filename)
66
        filename_rel = filename
67
68
    # (Note: files are executed by their owners, not the logged in user.
69
    # This ensures users are responsible for their own programs and also
70
    # allows them to be executed by the public).
71
72
    # Split up req.path again, this time with respect to the jail
73
    (working_dir, _) = os.path.split(filename_abs)
74
    # jail_dir is the absolute jail directory.
75
    # path is the filename relative to the user's jail.
76
    # working_dir is the directory containing the file relative to the user's
77
    # jail.
78
    # (Note that paths "relative" to the jail actually begin with a '/' as
79
    # they are absolute in the jailspace)
80
1770 by David Coles
interpret: Make fixup_env use a user object rather than path munging...
81
    return interpreter(owner, jail_dir, working_dir, filename_abs, req,
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
82
                       gentle, overrides=overrides)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
83
84
class CGIFlags:
85
    """Stores flags regarding the state of reading CGI output.
86
       If this is to be gentle, detection of invalid headers will result in an
87
       HTML warning."""
88
    def __init__(self, begentle=True):
89
        self.gentle = begentle
90
        self.started_cgi_body = False
91
        self.got_cgi_headers = False
92
        self.wrote_html_warning = False
93
        self.linebuf = ""
94
        self.headers = {}       # Header names : values
95
1770 by David Coles
interpret: Make fixup_env use a user object rather than path munging...
96
def execute_cgi(interpreter, owner, jail_dir, working_dir, script_path,
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
97
                req, gentle, overrides=None):
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
98
    """
99
    trampoline: Full path on the local system to the CGI wrapper program
100
        being executed.
1770 by David Coles
interpret: Make fixup_env use a user object rather than path munging...
101
    owner: User object of the owner of the file.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
102
    jail_dir: Absolute path of owner's jail directory.
103
    working_dir: Directory containing the script file relative to owner's
104
        jail.
105
    script_path: CGI script relative to the owner's jail.
106
    req: IVLE request object.
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
107
    gentle: ?
108
    overrides: A dict mapping env var names to strings, to override arbitrary
109
        environment variables in the resulting CGI environent.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
110
111
    The called CGI wrapper application shall be called using popen and receive
112
    the HTTP body on stdin. It shall receive the CGI environment variables to
113
    its environment.
114
    """
115
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
116
    trampoline = os.path.join(req.config['paths']['lib'], 'trampoline')
117
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
118
    # Support no-op trampoline runs.
119
    if interpreter is None:
120
        interpreter = '/bin/true'
121
        script_path = ''
122
        noop = True
123
    else:
124
        noop = False
125
126
    # Get the student program's directory and execute it from that context.
127
    (tramp_dir, _) = os.path.split(trampoline)
128
129
    # TODO: Don't create a file if the body length is known to be 0
130
    # Write the HTTP body to a temporary file so it can be passed as a *real*
131
    # file to popen.
132
    f = os.tmpfile()
133
    body = req.read() if not noop else None
134
    if body is not None:
135
        f.write(body)
136
        f.flush()
137
        f.seek(0)       # Rewind, for reading
138
139
    # Set up the environment
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
140
    environ = cgi_environ(req, script_path, owner, overrides=overrides)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
141
142
    # usage: tramp uid jail_dir working_dir script_path
1770 by David Coles
interpret: Make fixup_env use a user object rather than path munging...
143
    cmd_line = [trampoline, str(owner.unixid),
144
            req.config['paths']['jails']['mounts'],
145
            req.config['paths']['jails']['src'],
146
            req.config['paths']['jails']['template'],
147
            jail_dir, working_dir, interpreter, script_path]
1646 by Matt Giuca
ivle.interpret: Fixed calls to Popen: Unicode strings are encoded as UTF-8. This fixes serve of non-executable files, but serve-of-python, diff, log and download still break on files with a unicode filename.
148
    # Popen doesn't like unicode strings. It hateses them.
149
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
150
                for s in cmd_line]
151
    pid = subprocess.Popen(cmd_line,
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
152
        stdin=f, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
1777 by David Coles
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.
153
        cwd=tramp_dir, env=environ)
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
154
155
    # We don't want any output! Bail out after the process terminates.
156
    if noop:
157
        pid.communicate()
158
        return
159
160
    # process_cgi_line: Reads a single line of CGI output and processes it.
161
    # Prints to req, and also does fancy HTML warnings if Content-Type
162
    # omitted.
163
    cgiflags = CGIFlags(gentle)
164
165
    # Read from the process's stdout into req
166
    data = pid.stdout.read(CGI_BLOCK_SIZE)
167
    while len(data) > 0:
168
        process_cgi_output(req, data, cgiflags)
169
        data = pid.stdout.read(CGI_BLOCK_SIZE)
170
171
    # If we haven't processed headers yet, now is a good time
172
    if not cgiflags.started_cgi_body:
173
        process_cgi_output(req, '\n', cgiflags)
174
175
    # If we wrote an HTML warning header, write the footer
176
    if cgiflags.wrote_html_warning:
177
        req.write("""</pre>
178
  </div>
179
</body>
180
</html>""")
181
182
def process_cgi_output(req, data, cgiflags):
183
    """Processes a chunk of CGI output. data is a string of arbitrary length;
184
    some arbitrary chunk of output written by the CGI script."""
185
    if cgiflags.started_cgi_body:
186
        if cgiflags.wrote_html_warning:
187
            # HTML escape text if wrote_html_warning
188
            req.write(cgi.escape(data))
189
        else:
190
            req.write(data)
191
    else:
192
        # Break data into lines of CGI header data. 
193
        linebuf = cgiflags.linebuf + data
194
        # First see if we can split all header data
195
        # We need to get the double CRLF- or LF-terminated headers, whichever
196
        # is smaller, as either sequence may appear somewhere in the body.
197
        usplit = linebuf.split('\n\n', 1)
198
        wsplit = linebuf.split('\r\n\r\n', 1)
199
        split = len(usplit[0]) > len(wsplit[0]) and wsplit or usplit
200
        if len(split) == 1:
201
            # Haven't seen all headers yet. Buffer and come back later.
202
            cgiflags.linebuf = linebuf
203
            return
204
205
        headers = split[0]
206
        data = split[1]
207
        cgiflags.linebuf = ""
208
        cgiflags.started_cgi_body = True
209
        # Process all the header lines
210
        split = headers.split('\r\n', 1)
211
        if len(split) == 1:
212
            split = headers.split('\n', 1)
213
        while True:
214
            process_cgi_header_line(req, split[0], cgiflags)
215
            if len(split) == 1: break
216
            headers = split[1]
217
            if cgiflags.wrote_html_warning:
218
                # We're done with headers. Treat the rest as data.
219
                data = headers + '\n' + data
220
                break
221
            split = headers.split('\r\n', 1)
222
            if len(split) == 1:
223
                split = headers.split('\n', 1)
224
1780 by William Grant
Don't try to create IVLEJailErrors out of CGI headers when we're executing student code.
225
        # If not executing in gentle mode (which presents CGI violations
226
        # to users nicely), check if this an internal IVLE error
227
        # condition.
228
        if not cgiflags.gentle:
229
            hs = cgiflags.headers
230
            if 'X-IVLE-Error-Type' in hs:
231
                try:
232
                    raise IVLEJailError(hs['X-IVLE-Error-Type'],
233
                                        hs['X-IVLE-Error-Message'],
234
                                        hs['X-IVLE-Error-Info'])
235
                except KeyError:
236
                    raise AssertionError("Bad error headers written by CGI.")
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
237
238
        # Check to make sure the required headers were written
239
        if cgiflags.wrote_html_warning or not cgiflags.gentle:
240
            # We already reported an error, that's enough
241
            pass
242
        elif "Content-Type" in cgiflags.headers:
243
            pass
244
        elif "Location" in cgiflags.headers:
245
            if ("Status" in cgiflags.headers and req.status >= 300
246
                and req.status < 400):
247
                pass
248
            else:
249
                message = """You did not write a valid status code for
250
the given location. To make a redirect, you may wish to try:</p>
251
<pre style="margin-left: 1em">Status: 302 Found
252
Location: &lt;redirect address&gt;</pre>"""
253
                write_html_warning(req, message)
254
                cgiflags.wrote_html_warning = True
255
        else:
256
            message = """You did not print a Content-Type header.
257
CGI requires that you print a "Content-Type". You may wish to try:</p>
258
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
259
            write_html_warning(req, message)
260
            cgiflags.wrote_html_warning = True
261
262
        # Call myself to flush out the extra bit of data we read
263
        process_cgi_output(req, data, cgiflags)
264
265
def process_cgi_header_line(req, line, cgiflags):
266
    """Process a line of CGI header data. line is a string representing a
267
    complete line of text, stripped and without the newline.
268
    """
269
    try:
270
        name, value = line.split(':', 1)
271
    except ValueError:
272
        # No colon. The user did not write valid headers.
273
        # If we are being gentle, we want to help the user understand what
274
        # went wrong. Otherwise, just admit we screwed up.
275
        warning = "Warning"
276
        if not cgiflags.gentle:
277
            message = """An unexpected server error has occured."""
278
            warning = "Error"
279
        elif len(cgiflags.headers) == 0:
280
            # First line was not a header line. We can assume this is not
281
            # a CGI app.
282
            message = """You did not print a CGI header.
283
CGI requires that you print a "Content-Type". You may wish to try:</p>
284
<pre style="margin-left: 1em">Content-Type: text/html</pre>"""
285
        else:
286
            # They printed some header at least, but there was an invalid
287
            # header.
288
            message = """You printed an invalid CGI header. You need to leave
289
a blank line after the headers, before writing the page contents."""
290
        write_html_warning(req, message, warning=warning)
291
        cgiflags.wrote_html_warning = True
292
        # Handle the rest of this line as normal data
293
        process_cgi_output(req, line + '\n', cgiflags)
294
        return
295
1799 by David Coles
Show warning for CGI header field-names which contain restricted characters.
296
    # Check if CGI field-name is valid
297
    CGI_SEPERATORS = set(['(', ')', '<', '>', '@', ',', ';', ':', '\\', '"',
298
            '/', '[', ']', '?', '=', '{', '}', ' ', '\t'])
299
    if any((char in CGI_SEPERATORS for char in name)):
300
        warning = "Warning"
301
        if not cgiflags.gentle:
302
            message = """An unexpected server error has occured."""
303
            warning = "Error"
304
        else:
305
            # Header contained illegal characters
306
            message = """You printed an invalid CGI header. CGI header
307
            field-names can not contain any of the following characters: 
308
            <code>( ) &lt; &gt; @ , ; : \\ " / [ ] ? = { } <em>SPACE 
309
            TAB</em></code>."""
310
        write_html_warning(req, message, warning=warning)
311
        cgiflags.wrote_html_warning = True
312
        # Handle the rest of this line as normal data
313
        process_cgi_output(req, line + '\n', cgiflags)
314
        return
315
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
316
    # Read CGI headers
317
    value = value.strip()
318
    if name == "Content-Type":
319
        req.content_type = value
320
    elif name == "Location":
321
        req.location = value
322
    elif name == "Status":
323
        # Must be an integer, followed by a space, and then the status line
324
        # which we ignore (seems like Apache has no way to send a custom
325
        # status line).
326
        try:
327
            req.status = int(value.split(' ', 1)[0])
328
        except ValueError:
329
            if not cgiflags.gentle:
330
                # This isn't user code, so it should be good.
331
                # Get us out of here!
332
                raise
333
            message = """The "Status" CGI header was invalid. You need to
334
print a number followed by a message, such as "302 Found"."""
335
            write_html_warning(req, message)
336
            cgiflags.wrote_html_warning = True
337
            # Handle the rest of this line as normal data
338
            process_cgi_output(req, line + '\n', cgiflags)
339
    else:
340
        # Generic HTTP header
341
        # FIXME: Security risk letting users write arbitrary headers?
342
        req.headers_out.add(name, value)
343
    cgiflags.headers[name] = value # FIXME: Only the last header will end up here.
344
345
def write_html_warning(req, text, warning="Warning"):
346
    """Prints an HTML warning about invalid CGI interaction on the part of the
347
    user. text may contain HTML markup."""
348
    req.content_type = "text/html"
349
    req.write("""<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
350
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
351
<html xmlns="http://www.w3.org/1999/xhtml">
352
<head>
353
  <meta http-equiv="Content-Type"
354
    content="text/html; charset=utf-8" />
355
</head>
356
<body style="margin: 0; padding: 0; font-family: sans-serif;">
357
  <div style="background-color: #faa; border-bottom: 1px solid black;
358
    padding: 8px;">
359
    <p><strong>%s</strong>: %s
360
  </div>
361
  <div style="margin: 8px;">
362
    <pre>
363
""" % (warning, text))
364
365
# Mapping of interpreter names (as given in conf/app/server.py) to
366
# interpreter functions.
367
368
interpreter_objects = {
369
    'cgi-python'
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
370
        : functools.partial(execute_cgi, "/usr/bin/python"),
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
371
    'noop'
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
372
        : functools.partial(execute_cgi, None),
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
373
    # Should also have:
374
    # cgi-generic
375
    # python-server-page
376
}
377
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
378
def cgi_environ(req, script_path, user, overrides=None):
1777 by David Coles
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.
379
    """Gets CGI variables from apache and makes a few changes for security and 
380
    correctness.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
381
382
    Does not modify req, only reads it.
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
383
384
    overrides: A dict mapping env var names to strings, to override arbitrary
385
        environment variables in the resulting CGI environent.
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
386
    """
1777 by David Coles
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.
387
    env = {}
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
388
    # Comments here are on the heavy side, explained carefully for security
389
    # reasons. Please read carefully before making changes.
1777 by David Coles
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.
390
    
391
    # This automatically asks mod_python to load up the CGI variables into the
392
    # environment (which is a good first approximation)
393
    for (k,v) in req.get_cgi_environ().items():
394
        env[k] = v
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
395
396
    # Remove DOCUMENT_ROOT and SCRIPT_FILENAME. Not part of CGI spec and
397
    # exposes unnecessary details about server.
398
    try:
399
        del env['DOCUMENT_ROOT']
400
    except: pass
401
    try:
402
        del env['SCRIPT_FILENAME']
403
    except: pass
404
405
    # Remove PATH. The PATH here is the path on the server machine; not useful
406
    # inside the jail. It may be a good idea to add another path, reflecting
407
    # the inside of the jail, but not done at this stage.
408
    try:
409
        del env['PATH']
410
    except: pass
411
412
    # CGI specifies that REMOTE_HOST SHOULD be set, and MAY just be set to
413
    # REMOTE_ADDR. Since Apache does not appear to set this, set it to
414
    # REMOTE_ADDR.
415
    if 'REMOTE_HOST' not in env and 'REMOTE_ADDR' in env:
416
        env['REMOTE_HOST'] = env['REMOTE_ADDR']
417
1099.3.14 by William Grant
ivle.interpret.fixup_environ() now sets PATH_INFO appropriately.
418
    env['PATH_INFO'] = ''
419
    del env['PATH_TRANSLATED']
420
421
    normuri = os.path.normpath(req.uri)
422
    env['SCRIPT_NAME'] = normuri
423
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
424
    # 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.
425
    # We don't care about these if the script is null (ie. noop).
426
    # XXX: We check for /home because we don't want to interfere with
427
    # CGIRequest, which fileservice still uses.
428
    if script_path and script_path.startswith('/home'):
429
        normscript = os.path.normpath(script_path)
430
1270 by William Grant
Rename to to_home_path, and use it in ivle.interpret.
431
        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.
432
433
        # PATH_INFO is wrong because the script doesn't physically exist.
434
        env['PATH_INFO'] = uri_into_jail[len(normscript):]
435
        if len(env['PATH_INFO']) > 0:
436
            env['SCRIPT_NAME'] = normuri[:-len(env['PATH_INFO'])]
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
437
438
    # SERVER_SOFTWARE is actually not Apache but IVLE, since we are
439
    # custom-making the CGI request.
1274 by William Grant
Move ivle.conf.ivle_version to ivle.__version__.
440
    env['SERVER_SOFTWARE'] = "IVLE/" + ivle.__version__
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
441
442
    # Additional environment variables
1770 by David Coles
interpret: Make fixup_env use a user object rather than path munging...
443
    username = user.login
1079 by William Grant
Merge setup-refactor branch. This completely breaks existing installations;
444
    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
445
1802 by Matt Giuca
ivle/interpret: execute_cgi and interpret_file now take an 'overrides' argument, which is a dict containing env vars to override in the CGI request.
446
    if overrides is not None:
447
        env.update(overrides)
1777 by David Coles
interpret: Don't mutate os.environ for execute_cgi, Set an environ on subprocess.Popen instead.
448
    return env
449
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
450
class ExecutionError(Exception):
451
    pass
452
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
453
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
454
    '''Execute a binary in a user's jail, returning the raw output.
455
456
    The binary is executed in the given working directory with the given
457
    args. A tuple of (stdout, stderr) is returned.
458
    '''
459
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
460
    tramp = os.path.join(config['paths']['lib'], 'trampoline')
461
    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
462
463
    # Fire up trampoline. Vroom, vroom.
1646 by Matt Giuca
ivle.interpret: Fixed calls to Popen: Unicode strings are encoded as UTF-8. This fixes serve of non-executable files, but serve-of-python, diff, log and download still break on files with a unicode filename.
464
    cmd_line = [tramp, str(user.unixid), config['paths']['jails']['mounts'],
1276 by William Grant
Drop ivle.conf usage from ivle.interpret.
465
         config['paths']['jails']['src'],
466
         config['paths']['jails']['template'],
1646 by Matt Giuca
ivle.interpret: Fixed calls to Popen: Unicode strings are encoded as UTF-8. This fixes serve of non-executable files, but serve-of-python, diff, log and download still break on files with a unicode filename.
467
         jail_dir, working_dir, binary] + args
468
    # Popen doesn't like unicode strings. It hateses them.
469
    cmd_line = [(s.encode('utf-8') if isinstance(s, unicode) else s)
470
                for s in cmd_line]
471
    proc = subprocess.Popen(cmd_line,
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
472
        stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1760 by William Grant
ivle.interpret.execute_raw now sets a clean environment, in particular with HOME set correctly.
473
        stderr=subprocess.PIPE, cwd=tramp_dir, close_fds=True,
474
        env={'HOME': os.path.join('/home', user.login),
1776 by David Coles
interpret: Hard code PATH for interpret_raw since it's not always set correctly in Apache threads
475
             'PATH': PATH,
1760 by William Grant
ivle.interpret.execute_raw now sets a clean environment, in particular with HOME set correctly.
476
             'USER': user.login,
477
             'LOGNAME': user.login})
1164 by William Grant
ivle.interpret.execute_raw() no longer breaks with lots of data.
478
479
    (stdout, stderr) = proc.communicate()
480
    exitcode = proc.returncode
1099.1.47 by William Grant
ivle.interpret#execute_raw: Add. Executes a script in a user's jail with
481
482
    if exitcode != 0:
1772 by David Coles
interpret: Fix execute_raw's printing of stderr - can't read pipe after communicate returns.
483
        raise ExecutionError('subprocess ended with code %d, stderr: "%s"' %
484
                             (exitcode, stderr))
1164 by William Grant
ivle.interpret.execute_raw() no longer breaks with lots of data.
485
    return (stdout, stderr)