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