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).
41
def _http_headers_in_from_cgi():
42
"""Returns a dictionary of HTTP headers and their values, reading from the
45
for k in os.environ.keys():
46
if k.startswith("HTTP_"):
47
# Change the case - underscores become - and each word is
49
varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
51
d[varname] = os.environ[k]
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.
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.
69
HTTP_SWITCHING_PROTOCOLS = 101
74
HTTP_NON_AUTHORITATIVE = 203
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
83
HTTP_NOT_MODIFIED = 304
85
HTTP_TEMPORARY_REDIRECT = 307
86
HTTP_BAD_REQUEST = 400
87
HTTP_UNAUTHORIZED = 401
88
HTTP_PAYMENT_REQUIRED = 402
91
HTTP_METHOD_NOT_ALLOWED = 405
92
HTTP_NOT_ACCEPTABLE = 406
93
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
94
HTTP_REQUEST_TIME_OUT = 408
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
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
118
"""Builds an CGI Request object from the current CGI environment.
119
This results in an object with all of the necessary methods and
122
self.headers_written = False
124
if ('SERVER_NAME' not in os.environ or
125
'REQUEST_METHOD' not in os.environ or
126
'REQUEST_URI' not in os.environ):
127
raise Exception("No CGI environment found")
129
# Determine if the browser used the public host name to make the
130
# request (in which case we are in "public mode")
131
if os.environ['SERVER_NAME'] == conf.public_host:
132
self.publicmode = True
134
self.publicmode = False
136
# Inherit values for the input members
137
self.method = os.environ['REQUEST_METHOD']
138
self.uri = os.environ['REQUEST_URI']
139
# Split the given path into the app (top-level dir) and sub-path
140
# (after first stripping away the root directory)
141
path = common.util.unmake_path(self.uri)
146
(self.app, self.path) = (common.util.split_path(path))
148
self.hostname = os.environ['SERVER_NAME']
149
self.headers_in = _http_headers_in_from_cgi()
150
self.headers_out = {}
152
# Default values for the output members
153
self.status = CGIRequest.HTTP_OK
154
self.content_type = None # Use Apache's default
156
self.title = None # Will be set by dispatch before passing to app
159
self.write_html_head_foot = False
160
self.got_common_vars = False
162
def __writeheaders(self):
163
"""Writes out the HTTP and HTML headers before any real data is
165
self.headers_written = True
166
if 'Content-Type' in self.headers_out:
167
self.content_type = self.headers_out['Content-Type']
168
if 'Location' in self.headers_out:
169
self.location = self.headers_out['Location']
171
# CGI allows for four response types: Document, Local Redirect, Client
172
# Redirect, and Client Redirect w/ Document
173
# XXX We do not allow Local Redirect
174
if self.location != None:
175
# This is a Client Redirect
176
print "Location: %s" % self.location
177
if self.content_type == None:
180
# Else: This is a Client Redirect with Document
181
print "Status: %d" % self.status
182
print "Content-Type: %s" % self.content_type
184
# This is a Document response
185
print "Content-Type: %s" % self.content_type
186
print "Status: %d" % self.status
188
# Print the other headers
189
for k,v in self.headers_out.items():
190
if k != 'Content-Type' and k != 'Location':
191
print "%s: %s" % (k, v)
193
# XXX write_html_head_foot not supported
194
#if self.write_html_head_foot:
195
# # Write the HTML header, pass "self" (request object)
196
# self.func_write_html_head(self)
197
# Print a blank line to signal the start of output
200
def ensure_headers_written(self):
201
"""Writes out the HTTP and HTML headers if they haven't already been
203
if not self.headers_written:
204
self.__writeheaders()
206
def write(self, string, flush=1):
207
"""Writes string directly to the client, then flushes the buffer,
208
unless flush is 0."""
210
if not self.headers_written:
211
self.__writeheaders()
212
if isinstance(string, unicode):
213
# Encode unicode strings as UTF-8
214
# (Otherwise cannot handle being written to a bytestream)
215
sys.stdout.write(string.encode('utf8'))
217
# 8-bit clean strings just get written directly.
218
# This includes binary strings.
219
sys.stdout.write(string)
222
"""Flushes the output buffer."""
225
def sendfile(self, filename):
226
"""Sends the named file directly to the client."""
227
if not self.headers_written:
228
self.__writeheaders()
232
sys.stdout.write(buf)
237
def read(self, len=None):
238
"""Reads at most len bytes directly from the client. (See mod_python
241
return sys.stdin.read()
243
return sys.stdin.read(len)
245
def throw_error(self, httpcode):
246
"""Writes out an HTTP error of the specified code. Exits the process,
247
so any code following this call will not be executed.
249
(This is justified because of the nature of CGI, it is a single-script
250
environment, there is no containing process which needs to catch an
253
httpcode: An HTTP response status code. Pass a constant from the
256
self.status = httpcode
257
self.content_type = "text/html"
258
# Emulate an Apache error
259
self.write("""<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
261
<title>%d Error</title>
264
<p>A %d error was triggered by a CGI app.</p>
266
""" % (httpcode, httpcode))
267
# Exit the process completely
271
def throw_redirect(self, location):
272
"""Writes out an HTTP redirect to the specified URL. Exits the
273
process, so any code following this call will not be executed.
275
httpcode: An HTTP response status code. Pass a constant from the
278
self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
279
self.location = location
280
self.ensure_headers_written()
282
sys.exit(self.status)
284
def get_session(self):
285
"""Returns a mod_python Session object for this request.
286
Note that this is dependent on mod_python and may need to change
287
interface if porting away from mod_python."""
288
# Cache the session object
289
if not hasattr(self, 'session'):
290
#self.session = Session.FileSession(self.apache_req)
292
# FIXME: How to get session?
295
def get_fieldstorage(self):
296
"""Returns a mod_python FieldStorage object for this request.
297
Note that this is dependent on mod_python and may need to change
298
interface if porting away from mod_python."""
299
# Cache the fieldstorage object
300
if not hasattr(self, 'fields'):
301
self.fields = cgi.FieldStorage()
304
def get_cgi_environ(self):
305
"""Returns the CGI environment emulation for this request. (Calls
306
add_common_vars). The environment is returned as a mapping
307
compatible with os.environ."""