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

414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
1
# IVLE - Informatics Virtual Learning Environment
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: cgirequest
19
# Author: Matt Giuca
20
# Date:   5/2/2007
21
22
# Presents a CGIRequest class which creates an object compatible with IVLE
23
# Request objects (the same interface exposed by www.dispatch.request) from a
24
# CGI script.
25
# This allows CGI scripts to create request objects and then pass them to
26
# normal IVLE handlers.
27
28
# NOTE: This object does not support write_html_head_foot (simply because we
29
# do not need it in its intended application: fileservice).
30
31
import sys
32
import os
33
import cgi
851 by wagrant
Give CGIRequest an exception handler which turns any exception into
34
import urllib
35
import traceback
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
36
37
import conf
423 by mattgiuca
common.cgirequest: Added some missing includes.
38
import common
39
import common.util
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
40
41
# Utility functions
42
43
def _http_headers_in_from_cgi():
44
    """Returns a dictionary of HTTP headers and their values, reading from the
45
    CGI environment."""
46
    d = {}
47
    for k in os.environ.keys():
48
        if k.startswith("HTTP_"):
49
            # Change the case - underscores become - and each word is
50
            # capitalised
51
            varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
52
                                k[5:].split('_')))
53
            d[varname] = os.environ[k]
54
    return d
55
56
class CGIRequest:
57
    """An IVLE request object, built from a CGI script. This is presented to
58
    the IVLE apps as a way of interacting with the CGI server.
59
    See dispatch.request for a full interface specification.
60
    """
61
62
    # COPIED from dispatch/request.py
63
    # Special code for an OK response.
64
    # Do not use HTTP_OK; for some reason Apache produces an "OK" error
65
    # message if you do that.
66
    OK  = 0
67
68
    # HTTP status codes
69
70
    HTTP_CONTINUE                     = 100
71
    HTTP_SWITCHING_PROTOCOLS          = 101
72
    HTTP_PROCESSING                   = 102
73
    HTTP_OK                           = 200
74
    HTTP_CREATED                      = 201
75
    HTTP_ACCEPTED                     = 202
76
    HTTP_NON_AUTHORITATIVE            = 203
77
    HTTP_NO_CONTENT                   = 204
78
    HTTP_RESET_CONTENT                = 205
79
    HTTP_PARTIAL_CONTENT              = 206
80
    HTTP_MULTI_STATUS                 = 207
81
    HTTP_MULTIPLE_CHOICES             = 300
82
    HTTP_MOVED_PERMANENTLY            = 301
83
    HTTP_MOVED_TEMPORARILY            = 302
84
    HTTP_SEE_OTHER                    = 303
85
    HTTP_NOT_MODIFIED                 = 304
86
    HTTP_USE_PROXY                    = 305
87
    HTTP_TEMPORARY_REDIRECT           = 307
88
    HTTP_BAD_REQUEST                  = 400
89
    HTTP_UNAUTHORIZED                 = 401
90
    HTTP_PAYMENT_REQUIRED             = 402
91
    HTTP_FORBIDDEN                    = 403
92
    HTTP_NOT_FOUND                    = 404
93
    HTTP_METHOD_NOT_ALLOWED           = 405
94
    HTTP_NOT_ACCEPTABLE               = 406
95
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
96
    HTTP_REQUEST_TIME_OUT             = 408
97
    HTTP_CONFLICT                     = 409
98
    HTTP_GONE                         = 410
99
    HTTP_LENGTH_REQUIRED              = 411
100
    HTTP_PRECONDITION_FAILED          = 412
101
    HTTP_REQUEST_ENTITY_TOO_LARGE     = 413
102
    HTTP_REQUEST_URI_TOO_LARGE        = 414
103
    HTTP_UNSUPPORTED_MEDIA_TYPE       = 415
104
    HTTP_RANGE_NOT_SATISFIABLE        = 416
105
    HTTP_EXPECTATION_FAILED           = 417
106
    HTTP_UNPROCESSABLE_ENTITY         = 422
107
    HTTP_LOCKED                       = 423
108
    HTTP_FAILED_DEPENDENCY            = 424
109
    HTTP_INTERNAL_SERVER_ERROR        = 500
110
    HTTP_NOT_IMPLEMENTED              = 501
111
    HTTP_BAD_GATEWAY                  = 502
112
    HTTP_SERVICE_UNAVAILABLE          = 503
113
    HTTP_GATEWAY_TIME_OUT             = 504
114
    HTTP_VERSION_NOT_SUPPORTED        = 505
115
    HTTP_VARIANT_ALSO_VARIES          = 506
116
    HTTP_INSUFFICIENT_STORAGE         = 507
117
    HTTP_NOT_EXTENDED                 = 510
118
119
    def __init__(self):
120
        """Builds an CGI Request object from the current CGI environment.
121
        This results in an object with all of the necessary methods and
122
        additional fields.
123
        """
124
        self.headers_written = False
125
419 by mattgiuca
cgirequest: Throws an exception if important CGI variables are not found.
126
        if ('SERVER_NAME' not in os.environ or
127
            'REQUEST_METHOD' not in os.environ or
773 by mattgiuca
cgirequest.py: Fixed req.path attribute, so it now DOES NOT include the
128
            'SCRIPT_NAME' not in os.environ or
129
            'PATH_INFO' not in os.environ):
419 by mattgiuca
cgirequest: Throws an exception if important CGI variables are not found.
130
            raise Exception("No CGI environment found")
131
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
132
        # Determine if the browser used the public host name to make the
133
        # request (in which case we are in "public mode")
134
        if os.environ['SERVER_NAME'] == conf.public_host:
135
            self.publicmode = True
136
        else:
137
            self.publicmode = False
138
139
        # Inherit values for the input members
140
        self.method = os.environ['REQUEST_METHOD']
773 by mattgiuca
cgirequest.py: Fixed req.path attribute, so it now DOES NOT include the
141
        self.uri = os.environ['SCRIPT_NAME'] + os.environ['PATH_INFO']
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
142
        # Split the given path into the app (top-level dir) and sub-path
143
        # (after first stripping away the root directory)
144
        path = common.util.unmake_path(self.uri)
145
        if self.publicmode:
146
            self.app = None
723 by dcoles
request: Ensure that the req.path is correct in public mode (should be
147
            (_, self.path) = (common.util.split_path(path))
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
148
        else:
149
            (self.app, self.path) = (common.util.split_path(path))
505 by mattgiuca
dispatch.html, consoleservice, userservice, interpret:
150
        self.user = None
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
151
        self.hostname = os.environ['SERVER_NAME']
152
        self.headers_in = _http_headers_in_from_cgi()
153
        self.headers_out = {}
154
155
        # Default values for the output members
156
        self.status = CGIRequest.HTTP_OK
157
        self.content_type = None        # Use Apache's default
158
        self.location = None
159
        self.title = None     # Will be set by dispatch before passing to app
160
        self.styles = []
161
        self.scripts = []
162
        self.write_html_head_foot = False
163
        self.got_common_vars = False
164
851 by wagrant
Give CGIRequest an exception handler which turns any exception into
165
166
    def install_error_handler(self):
167
        '''Install our exception handler as the default.'''
168
        sys.excepthook = self.handle_unknown_exception
169
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
170
    def __writeheaders(self):
171
        """Writes out the HTTP and HTML headers before any real data is
172
        written."""
173
        self.headers_written = True
174
        if 'Content-Type' in self.headers_out:
175
            self.content_type = self.headers_out['Content-Type']
176
        if 'Location' in self.headers_out:
177
            self.location = self.headers_out['Location']
178
179
        # CGI allows for four response types: Document, Local Redirect, Client
180
        # Redirect, and Client Redirect w/ Document
181
        # XXX We do not allow Local Redirect
182
        if self.location != None:
183
            # This is a Client Redirect
184
            print "Location: %s" % self.location
185
            if self.content_type == None:
186
                # Just redirect
187
                return
188
            # Else: This is a Client Redirect with Document
189
            print "Status: %d" % self.status
190
            print "Content-Type: %s" % self.content_type
191
        else:
192
            # This is a Document response
193
            print "Content-Type: %s" % self.content_type
194
            print "Status: %d" % self.status
195
196
        # Print the other headers
197
        for k,v in self.headers_out.items():
198
            if k != 'Content-Type' and k != 'Location':
199
                print "%s: %s" % (k, v)
200
201
        # XXX write_html_head_foot not supported
202
        #if self.write_html_head_foot:
203
        #    # Write the HTML header, pass "self" (request object)
204
        #    self.func_write_html_head(self)
205
        # Print a blank line to signal the start of output
206
        print
207
208
    def ensure_headers_written(self):
209
        """Writes out the HTTP and HTML headers if they haven't already been
210
        written."""
211
        if not self.headers_written:
212
            self.__writeheaders()
213
214
    def write(self, string, flush=1):
215
        """Writes string directly to the client, then flushes the buffer,
216
        unless flush is 0."""
217
218
        if not self.headers_written:
219
            self.__writeheaders()
220
        if isinstance(string, unicode):
221
            # Encode unicode strings as UTF-8
222
            # (Otherwise cannot handle being written to a bytestream)
223
            sys.stdout.write(string.encode('utf8'))
224
        else:
225
            # 8-bit clean strings just get written directly.
226
            # This includes binary strings.
227
            sys.stdout.write(string)
228
229
    def flush(self):
230
        """Flushes the output buffer."""
231
        sys.stdout.flush()
232
233
    def sendfile(self, filename):
234
        """Sends the named file directly to the client."""
235
        if not self.headers_written:
236
            self.__writeheaders()
237
        f = open(filename)
238
        buf = f.read(1024)
239
        while len(buf) > 0:
436 by drtomc
fileservice: Make things less broken than they were. No claims of perfection yet! Unpacking form data with cgi.py is AWFUL.
240
            sys.stdout.write(buf)
241
            sys.stdout.flush()
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
242
            buf = f.read(1024)
243
        f.close()
244
245
    def read(self, len=None):
246
        """Reads at most len bytes directly from the client. (See mod_python
247
        Request.read)."""
248
        if len is None:
249
            return sys.stdin.read()
250
        else:
251
            return sys.stdin.read(len)
252
649 by mattgiuca
lib/common/cgirequest.py: Added "message" arg to req.throw_error.
253
    def throw_error(self, httpcode, message):
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
254
        """Writes out an HTTP error of the specified code. Exits the process,
255
        so any code following this call will not be executed.
256
257
        (This is justified because of the nature of CGI, it is a single-script
258
        environment, there is no containing process which needs to catch an
259
        exception).
260
261
        httpcode: An HTTP response status code. Pass a constant from the
262
        Request class.
263
        """
851 by wagrant
Give CGIRequest an exception handler which turns any exception into
264
        raise common.util.IVLEError(httpcode, message)
265
266
    def handle_unknown_exception(self, exc_type, exc_value, exc_tb):
267
        if exc_type is common.util.IVLEError:
268
            self.headers_out['X-IVLE-Error-Code'] = exc_value.httpcode
269
270
        self.headers_out['X-IVLE-Error-Type'] = exc_type.__name__
271
272
        try:
273
            self.headers_out['X-IVLE-Error-Message'] = exc_value.message
274
        except AttributeError:
275
            pass
276
277
        self.headers_out['X-IVLE-Error-Info'] = urllib.quote(''.join(
278
              traceback.format_exception(exc_type, exc_value, exc_tb)))
845 by wagrant
CGIRequest.throw_error() will now set the IVLEError HTTP headers.
279
        self.status = 500
843 by wagrant
Give interpret_file a gentle mode (on by default, to avoid change in
280
        self.ensure_headers_written()
845 by wagrant
CGIRequest.throw_error() will now set the IVLEError HTTP headers.
281
        self.write('An internal IVLE error has occurred.')
843 by wagrant
Give interpret_file a gentle mode (on by default, to avoid change in
282
        self.flush()
283
        sys.exit(self.status)
414 by mattgiuca
Added common/cgirequest.py. This takes the CGI environment and wraps it in a
284
285
    def throw_redirect(self, location):
286
        """Writes out an HTTP redirect to the specified URL. Exits the
287
        process, so any code following this call will not be executed.
288
289
        httpcode: An HTTP response status code. Pass a constant from the
290
        Request class.
291
        """
292
        self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
293
        self.location = location
294
        self.ensure_headers_written()
295
        self.flush()
296
        sys.exit(self.status)
297
298
    def get_session(self):
299
        """Returns a mod_python Session object for this request.
300
        Note that this is dependent on mod_python and may need to change
301
        interface if porting away from mod_python."""
302
        # Cache the session object
303
        if not hasattr(self, 'session'):
304
            #self.session = Session.FileSession(self.apache_req)
305
            self.session = None
306
            # FIXME: How to get session?
307
        return self.session
308
309
    def get_fieldstorage(self):
310
        """Returns a mod_python FieldStorage object for this request.
311
        Note that this is dependent on mod_python and may need to change
312
        interface if porting away from mod_python."""
313
        # Cache the fieldstorage object
314
        if not hasattr(self, 'fields'):
315
            self.fields = cgi.FieldStorage()
316
        return self.fields
317
318
    def get_cgi_environ(self):
319
        """Returns the CGI environment emulation for this request. (Calls
320
        add_common_vars). The environment is returned as a mapping
321
        compatible with os.environ."""
322
        return os.environ