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
'SCRIPT_NAME' not in os.environ or
127
'PATH_INFO' not in os.environ):
128
raise Exception("No CGI environment found")
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
135
self.publicmode = False
137
# Inherit values for the input members
138
self.method = os.environ['REQUEST_METHOD']
139
self.uri = os.environ['SCRIPT_NAME'] + os.environ['PATH_INFO']
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)
145
(_, self.path) = (common.util.split_path(path))
147
(self.app, self.path) = (common.util.split_path(path))
149
self.hostname = os.environ['SERVER_NAME']
150
self.headers_in = _http_headers_in_from_cgi()
151
self.headers_out = {}
153
# Default values for the output members
154
self.status = CGIRequest.HTTP_OK
155
self.content_type = None # Use Apache's default
157
self.title = None # Will be set by dispatch before passing to app
160
self.write_html_head_foot = False
161
self.got_common_vars = False
163
def __writeheaders(self):
164
"""Writes out the HTTP and HTML headers before any real data is
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']
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:
181
# Else: This is a Client Redirect with Document
182
print "Status: %d" % self.status
183
print "Content-Type: %s" % self.content_type
185
# This is a Document response
186
print "Content-Type: %s" % self.content_type
187
print "Status: %d" % self.status
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)
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
201
def ensure_headers_written(self):
202
"""Writes out the HTTP and HTML headers if they haven't already been
204
if not self.headers_written:
205
self.__writeheaders()
207
def write(self, string, flush=1):
208
"""Writes string directly to the client, then flushes the buffer,
209
unless flush is 0."""
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'))
218
# 8-bit clean strings just get written directly.
219
# This includes binary strings.
220
sys.stdout.write(string)
223
"""Flushes the output buffer."""
226
def sendfile(self, filename):
227
"""Sends the named file directly to the client."""
228
if not self.headers_written:
229
self.__writeheaders()
233
sys.stdout.write(buf)
238
def read(self, len=None):
239
"""Reads at most len bytes directly from the client. (See mod_python
242
return sys.stdin.read()
244
return sys.stdin.read(len)
246
def throw_error(self, httpcode, message):
247
"""Writes out an HTTP error of the specified code. Exits the process,
248
so any code following this call will not be executed.
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
254
httpcode: An HTTP response status code. Pass a constant from the
257
raise common.util.IVLEError(httpcode, message)
259
def throw_redirect(self, location):
260
"""Writes out an HTTP redirect to the specified URL. Exits the
261
process, so any code following this call will not be executed.
263
httpcode: An HTTP response status code. Pass a constant from the
266
self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
267
self.location = location
268
self.ensure_headers_written()
270
sys.exit(self.status)
272
def get_session(self):
273
"""Returns a mod_python Session object for this request.
274
Note that this is dependent on mod_python and may need to change
275
interface if porting away from mod_python."""
276
# Cache the session object
277
if not hasattr(self, 'session'):
278
#self.session = Session.FileSession(self.apache_req)
280
# FIXME: How to get session?
283
def get_fieldstorage(self):
284
"""Returns a mod_python FieldStorage object for this request.
285
Note that this is dependent on mod_python and may need to change
286
interface if porting away from mod_python."""
287
# Cache the fieldstorage object
288
if not hasattr(self, 'fields'):
289
self.fields = cgi.FieldStorage()
292
def get_cgi_environ(self):
293
"""Returns the CGI environment emulation for this request. (Calls
294
add_common_vars). The environment is returned as a mapping
295
compatible with os.environ."""