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).
39
def _http_headers_in_from_cgi():
40
"""Returns a dictionary of HTTP headers and their values, reading from the
43
for k in os.environ.keys():
44
if k.startswith("HTTP_"):
45
# Change the case - underscores become - and each word is
47
varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
49
d[varname] = os.environ[k]
53
"""An IVLE request object, built from a CGI script. This is presented to
54
the IVLE apps as a way of interacting with the CGI server.
55
See dispatch.request for a full interface specification.
58
# COPIED from dispatch/request.py
59
# Special code for an OK response.
60
# Do not use HTTP_OK; for some reason Apache produces an "OK" error
61
# message if you do that.
67
HTTP_SWITCHING_PROTOCOLS = 101
72
HTTP_NON_AUTHORITATIVE = 203
74
HTTP_RESET_CONTENT = 205
75
HTTP_PARTIAL_CONTENT = 206
76
HTTP_MULTI_STATUS = 207
77
HTTP_MULTIPLE_CHOICES = 300
78
HTTP_MOVED_PERMANENTLY = 301
79
HTTP_MOVED_TEMPORARILY = 302
81
HTTP_NOT_MODIFIED = 304
83
HTTP_TEMPORARY_REDIRECT = 307
84
HTTP_BAD_REQUEST = 400
85
HTTP_UNAUTHORIZED = 401
86
HTTP_PAYMENT_REQUIRED = 402
89
HTTP_METHOD_NOT_ALLOWED = 405
90
HTTP_NOT_ACCEPTABLE = 406
91
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
92
HTTP_REQUEST_TIME_OUT = 408
95
HTTP_LENGTH_REQUIRED = 411
96
HTTP_PRECONDITION_FAILED = 412
97
HTTP_REQUEST_ENTITY_TOO_LARGE = 413
98
HTTP_REQUEST_URI_TOO_LARGE = 414
99
HTTP_UNSUPPORTED_MEDIA_TYPE = 415
100
HTTP_RANGE_NOT_SATISFIABLE = 416
101
HTTP_EXPECTATION_FAILED = 417
102
HTTP_UNPROCESSABLE_ENTITY = 422
104
HTTP_FAILED_DEPENDENCY = 424
105
HTTP_INTERNAL_SERVER_ERROR = 500
106
HTTP_NOT_IMPLEMENTED = 501
107
HTTP_BAD_GATEWAY = 502
108
HTTP_SERVICE_UNAVAILABLE = 503
109
HTTP_GATEWAY_TIME_OUT = 504
110
HTTP_VERSION_NOT_SUPPORTED = 505
111
HTTP_VARIANT_ALSO_VARIES = 506
112
HTTP_INSUFFICIENT_STORAGE = 507
113
HTTP_NOT_EXTENDED = 510
116
"""Builds an CGI Request object from the current CGI environment.
117
This results in an object with all of the necessary methods and
120
self.headers_written = False
122
if ('SERVER_NAME' not in os.environ or
123
'REQUEST_METHOD' not in os.environ or
124
'REQUEST_URI' not in os.environ):
125
raise Exception("No CGI environment found")
127
# Determine if the browser used the public host name to make the
128
# request (in which case we are in "public mode")
129
if os.environ['SERVER_NAME'] == conf.public_host:
130
self.publicmode = True
132
self.publicmode = False
134
# Inherit values for the input members
135
self.method = os.environ['REQUEST_METHOD']
136
self.uri = os.environ['REQUEST_URI']
137
# Split the given path into the app (top-level dir) and sub-path
138
# (after first stripping away the root directory)
139
path = common.util.unmake_path(self.uri)
144
(self.app, self.path) = (common.util.split_path(path))
146
self.hostname = os.environ['SERVER_NAME']
147
self.headers_in = _http_headers_in_from_cgi()
148
self.headers_out = {}
150
# Default values for the output members
151
self.status = CGIRequest.HTTP_OK
152
self.content_type = None # Use Apache's default
154
self.title = None # Will be set by dispatch before passing to app
157
self.write_html_head_foot = False
158
self.got_common_vars = False
160
def __writeheaders(self):
161
"""Writes out the HTTP and HTML headers before any real data is
163
self.headers_written = True
164
if 'Content-Type' in self.headers_out:
165
self.content_type = self.headers_out['Content-Type']
166
if 'Location' in self.headers_out:
167
self.location = self.headers_out['Location']
169
# CGI allows for four response types: Document, Local Redirect, Client
170
# Redirect, and Client Redirect w/ Document
171
# XXX We do not allow Local Redirect
172
if self.location != None:
173
# This is a Client Redirect
174
print "Location: %s" % self.location
175
if self.content_type == None:
178
# Else: This is a Client Redirect with Document
179
print "Status: %d" % self.status
180
print "Content-Type: %s" % self.content_type
182
# This is a Document response
183
print "Content-Type: %s" % self.content_type
184
print "Status: %d" % self.status
186
# Print the other headers
187
for k,v in self.headers_out.items():
188
if k != 'Content-Type' and k != 'Location':
189
print "%s: %s" % (k, v)
191
# XXX write_html_head_foot not supported
192
#if self.write_html_head_foot:
193
# # Write the HTML header, pass "self" (request object)
194
# self.func_write_html_head(self)
195
# Print a blank line to signal the start of output
198
def ensure_headers_written(self):
199
"""Writes out the HTTP and HTML headers if they haven't already been
201
if not self.headers_written:
202
self.__writeheaders()
204
def write(self, string, flush=1):
205
"""Writes string directly to the client, then flushes the buffer,
206
unless flush is 0."""
208
if not self.headers_written:
209
self.__writeheaders()
210
if isinstance(string, unicode):
211
# Encode unicode strings as UTF-8
212
# (Otherwise cannot handle being written to a bytestream)
213
sys.stdout.write(string.encode('utf8'))
215
# 8-bit clean strings just get written directly.
216
# This includes binary strings.
217
sys.stdout.write(string)
220
"""Flushes the output buffer."""
223
def sendfile(self, filename):
224
"""Sends the named file directly to the client."""
225
if not self.headers_written:
226
self.__writeheaders()
230
sys.stdout.flush(buf)
234
def read(self, len=None):
235
"""Reads at most len bytes directly from the client. (See mod_python
238
return sys.stdin.read()
240
return sys.stdin.read(len)
242
def throw_error(self, httpcode):
243
"""Writes out an HTTP error of the specified code. Exits the process,
244
so any code following this call will not be executed.
246
(This is justified because of the nature of CGI, it is a single-script
247
environment, there is no containing process which needs to catch an
250
httpcode: An HTTP response status code. Pass a constant from the
253
self.status = httpcode
254
self.content_type = "text/html"
255
# Emulate an Apache error
256
self.write("""<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
258
<title>%d Error</title>
261
<p>A %d error was triggered by a CGI app.</p>
263
""" % (httpcode, httpcode))
264
# Exit the process completely
268
def throw_redirect(self, location):
269
"""Writes out an HTTP redirect to the specified URL. Exits the
270
process, so any code following this call will not be executed.
272
httpcode: An HTTP response status code. Pass a constant from the
275
self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
276
self.location = location
277
self.ensure_headers_written()
279
sys.exit(self.status)
281
def get_session(self):
282
"""Returns a mod_python Session object for this request.
283
Note that this is dependent on mod_python and may need to change
284
interface if porting away from mod_python."""
285
# Cache the session object
286
if not hasattr(self, 'session'):
287
#self.session = Session.FileSession(self.apache_req)
289
# FIXME: How to get session?
292
def get_fieldstorage(self):
293
"""Returns a mod_python FieldStorage object for this request.
294
Note that this is dependent on mod_python and may need to change
295
interface if porting away from mod_python."""
296
# Cache the fieldstorage object
297
if not hasattr(self, 'fields'):
298
self.fields = cgi.FieldStorage()
301
def get_cgi_environ(self):
302
"""Returns the CGI environment emulation for this request. (Calls
303
add_common_vars). The environment is returned as a mapping
304
compatible with os.environ."""