1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2008 The University of Melbourne
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.
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.
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
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
25
# This allows CGI scripts to create request objects and then pass them to
26
# normal IVLE handlers.
28
# NOTE: This object does not support write_html_head_foot (simply because we
29
# do not need it in its intended application: fileservice).
43
def _http_headers_in_from_cgi():
44
"""Returns a dictionary of HTTP headers and their values, reading from the
47
for k in os.environ.keys():
48
if k.startswith("HTTP_"):
49
# Change the case - underscores become - and each word is
51
varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
53
d[varname] = os.environ[k]
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.
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.
71
HTTP_SWITCHING_PROTOCOLS = 101
76
HTTP_NON_AUTHORITATIVE = 203
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
85
HTTP_NOT_MODIFIED = 304
87
HTTP_TEMPORARY_REDIRECT = 307
88
HTTP_BAD_REQUEST = 400
89
HTTP_UNAUTHORIZED = 401
90
HTTP_PAYMENT_REQUIRED = 402
93
HTTP_METHOD_NOT_ALLOWED = 405
94
HTTP_NOT_ACCEPTABLE = 406
95
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
96
HTTP_REQUEST_TIME_OUT = 408
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
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
120
"""Builds an CGI Request object from the current CGI environment.
121
This results in an object with all of the necessary methods and
124
self.headers_written = False
126
if ('SERVER_NAME' not in os.environ or
127
'REQUEST_METHOD' not in os.environ or
128
'SCRIPT_NAME' not in os.environ or
129
'PATH_INFO' not in os.environ):
130
raise Exception("No CGI environment found")
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
137
self.publicmode = False
139
# Inherit values for the input members
140
self.method = os.environ['REQUEST_METHOD']
141
self.uri = os.environ['SCRIPT_NAME'] + os.environ['PATH_INFO']
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)
147
(_, self.path) = (common.util.split_path(path))
149
(self.app, self.path) = (common.util.split_path(path))
151
self.hostname = os.environ['SERVER_NAME']
152
self.headers_in = _http_headers_in_from_cgi()
153
self.headers_out = {}
155
# Default values for the output members
156
self.status = CGIRequest.HTTP_OK
157
self.content_type = None # Use Apache's default
159
self.title = None # Will be set by dispatch before passing to app
162
self.write_html_head_foot = False
163
self.got_common_vars = False
166
def install_error_handler(self):
167
'''Install our exception handler as the default.'''
168
sys.excepthook = self.handle_unknown_exception
170
def __writeheaders(self):
171
"""Writes out the HTTP and HTML headers before any real data is
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']
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:
188
# Else: This is a Client Redirect with Document
189
print "Status: %d" % self.status
190
print "Content-Type: %s" % self.content_type
192
# This is a Document response
193
print "Content-Type: %s" % self.content_type
194
print "Status: %d" % self.status
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)
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
208
def ensure_headers_written(self):
209
"""Writes out the HTTP and HTML headers if they haven't already been
211
if not self.headers_written:
212
self.__writeheaders()
214
def write(self, string, flush=1):
215
"""Writes string directly to the client, then flushes the buffer,
216
unless flush is 0."""
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'))
225
# 8-bit clean strings just get written directly.
226
# This includes binary strings.
227
sys.stdout.write(string)
230
"""Flushes the output buffer."""
233
def sendfile(self, filename):
234
"""Sends the named file directly to the client."""
235
if not self.headers_written:
236
self.__writeheaders()
240
sys.stdout.write(buf)
245
def read(self, len=None):
246
"""Reads at most len bytes directly from the client. (See mod_python
249
return sys.stdin.read()
251
return sys.stdin.read(len)
253
def throw_error(self, httpcode, message):
254
"""Writes out an HTTP error of the specified code. Exits the process,
255
so any code following this call will not be executed.
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
261
httpcode: An HTTP response status code. Pass a constant from the
264
raise common.util.IVLEError(httpcode, message)
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
270
self.headers_out['X-IVLE-Error-Type'] = exc_type.__name__
273
self.headers_out['X-IVLE-Error-Message'] = exc_value.message
274
except AttributeError:
277
self.headers_out['X-IVLE-Error-Info'] = urllib.quote(''.join(
278
traceback.format_exception(exc_type, exc_value, exc_tb)))
280
self.ensure_headers_written()
281
self.write('An internal IVLE error has occurred.')
283
sys.exit(self.status)
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.
289
httpcode: An HTTP response status code. Pass a constant from the
292
self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
293
self.location = location
294
self.ensure_headers_written()
296
sys.exit(self.status)
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)
306
# FIXME: How to get session?
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()
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."""