1079
by William Grant
Merge setup-refactor branch. This completely breaks existing installations; |
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 |
import sys |
|
29 |
import os |
|
30 |
import cgi |
|
31 |
import urllib |
|
32 |
import traceback |
|
33 |
||
34 |
import ivle.conf |
|
35 |
import ivle.util |
|
36 |
||
37 |
# Utility functions
|
|
38 |
||
39 |
def _http_headers_in_from_cgi(): |
|
40 |
"""Returns a dictionary of HTTP headers and their values, reading from the
|
|
41 |
CGI environment."""
|
|
42 |
d = {} |
|
43 |
for k in os.environ.keys(): |
|
44 |
if k.startswith("HTTP_"): |
|
45 |
# Change the case - underscores become - and each word is
|
|
46 |
# capitalised
|
|
47 |
varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(), |
|
48 |
k[5:].split('_'))) |
|
49 |
d[varname] = os.environ[k] |
|
50 |
return d |
|
51 |
||
52 |
class CGIRequest: |
|
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.
|
|
56 |
"""
|
|
57 |
||
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.
|
|
62 |
OK = 0 |
|
63 |
||
64 |
# HTTP status codes
|
|
65 |
||
66 |
HTTP_CONTINUE = 100 |
|
67 |
HTTP_SWITCHING_PROTOCOLS = 101 |
|
68 |
HTTP_PROCESSING = 102 |
|
69 |
HTTP_OK = 200 |
|
70 |
HTTP_CREATED = 201 |
|
71 |
HTTP_ACCEPTED = 202 |
|
72 |
HTTP_NON_AUTHORITATIVE = 203 |
|
73 |
HTTP_NO_CONTENT = 204 |
|
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 |
|
80 |
HTTP_SEE_OTHER = 303 |
|
81 |
HTTP_NOT_MODIFIED = 304 |
|
82 |
HTTP_USE_PROXY = 305 |
|
83 |
HTTP_TEMPORARY_REDIRECT = 307 |
|
84 |
HTTP_BAD_REQUEST = 400 |
|
85 |
HTTP_UNAUTHORIZED = 401 |
|
86 |
HTTP_PAYMENT_REQUIRED = 402 |
|
87 |
HTTP_FORBIDDEN = 403 |
|
88 |
HTTP_NOT_FOUND = 404 |
|
89 |
HTTP_METHOD_NOT_ALLOWED = 405 |
|
90 |
HTTP_NOT_ACCEPTABLE = 406 |
|
91 |
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407 |
|
92 |
HTTP_REQUEST_TIME_OUT = 408 |
|
93 |
HTTP_CONFLICT = 409 |
|
94 |
HTTP_GONE = 410 |
|
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 |
|
103 |
HTTP_LOCKED = 423 |
|
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 |
|
114 |
||
115 |
def __init__(self): |
|
116 |
"""Builds an CGI Request object from the current CGI environment.
|
|
117 |
This results in an object with all of the necessary methods and
|
|
118 |
additional fields.
|
|
119 |
"""
|
|
120 |
self.headers_written = False |
|
121 |
||
122 |
if ('SERVER_NAME' not in os.environ or |
|
123 |
'REQUEST_METHOD' not in os.environ or |
|
124 |
'SCRIPT_NAME' not in os.environ or |
|
125 |
'PATH_INFO' not in os.environ): |
|
126 |
raise Exception("No CGI environment found") |
|
127 |
||
128 |
# Determine if the browser used the public host name to make the
|
|
129 |
# request (in which case we are in "public mode")
|
|
130 |
if os.environ['SERVER_NAME'] == ivle.conf.public_host: |
|
131 |
self.publicmode = True |
|
132 |
else: |
|
133 |
self.publicmode = False |
|
134 |
||
135 |
# Inherit values for the input members
|
|
136 |
self.method = os.environ['REQUEST_METHOD'] |
|
137 |
self.uri = os.environ['SCRIPT_NAME'] + os.environ['PATH_INFO'] |
|
138 |
# Split the given path into the app (top-level dir) and sub-path
|
|
139 |
# (after first stripping away the root directory)
|
|
140 |
path = ivle.util.unmake_path(self.uri) |
|
141 |
if self.publicmode: |
|
142 |
self.app = None |
|
143 |
(_, self.path) = (ivle.util.split_path(path)) |
|
144 |
else: |
|
145 |
(self.app, self.path) = (ivle.util.split_path(path)) |
|
146 |
self.user = None |
|
147 |
self.hostname = os.environ['SERVER_NAME'] |
|
148 |
self.headers_in = _http_headers_in_from_cgi() |
|
149 |
self.headers_out = {} |
|
150 |
||
151 |
# Default values for the output members
|
|
152 |
self.status = CGIRequest.HTTP_OK |
|
153 |
self.content_type = None # Use Apache's default |
|
154 |
self.location = None |
|
155 |
self.styles = [] |
|
156 |
self.scripts = [] |
|
157 |
self.got_common_vars = False |
|
158 |
||
159 |
||
160 |
def install_error_handler(self): |
|
161 |
'''Install our exception handler as the default.'''
|
|
162 |
sys.excepthook = self.handle_unknown_exception |
|
163 |
||
164 |
def __writeheaders(self): |
|
165 |
"""Writes out the HTTP and HTML headers before any real data is
|
|
166 |
written."""
|
|
167 |
self.headers_written = True |
|
168 |
if 'Content-Type' in self.headers_out: |
|
169 |
self.content_type = self.headers_out['Content-Type'] |
|
170 |
if 'Location' in self.headers_out: |
|
171 |
self.location = self.headers_out['Location'] |
|
172 |
||
173 |
# CGI allows for four response types: Document, Local Redirect, Client
|
|
174 |
# Redirect, and Client Redirect w/ Document
|
|
175 |
# XXX We do not allow Local Redirect
|
|
176 |
if self.location != None: |
|
177 |
# This is a Client Redirect
|
|
178 |
print "Location: %s" % self.location |
|
179 |
if self.content_type == None: |
|
180 |
# Just redirect
|
|
181 |
return
|
|
182 |
# Else: This is a Client Redirect with Document
|
|
183 |
print "Status: %d" % self.status |
|
184 |
print "Content-Type: %s" % self.content_type |
|
185 |
else: |
|
186 |
# This is a Document response
|
|
187 |
print "Content-Type: %s" % self.content_type |
|
188 |
print "Status: %d" % self.status |
|
189 |
||
190 |
# Print the other headers
|
|
191 |
for k,v in self.headers_out.items(): |
|
192 |
if k != 'Content-Type' and k != 'Location': |
|
193 |
print "%s: %s" % (k, v) |
|
194 |
||
195 |
# Print a blank line to signal the start of output
|
|
196 |
print
|
|
197 |
||
198 |
def ensure_headers_written(self): |
|
199 |
"""Writes out the HTTP and HTML headers if they haven't already been
|
|
200 |
written."""
|
|
201 |
if not self.headers_written: |
|
202 |
self.__writeheaders() |
|
203 |
||
204 |
def write(self, string, flush=1): |
|
205 |
"""Writes string directly to the client, then flushes the buffer,
|
|
206 |
unless flush is 0."""
|
|
207 |
||
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')) |
|
214 |
else: |
|
215 |
# 8-bit clean strings just get written directly.
|
|
216 |
# This includes binary strings.
|
|
217 |
sys.stdout.write(string) |
|
218 |
||
219 |
def flush(self): |
|
220 |
"""Flushes the output buffer."""
|
|
221 |
sys.stdout.flush() |
|
222 |
||
223 |
def sendfile(self, filename): |
|
224 |
"""Sends the named file directly to the client."""
|
|
225 |
if not self.headers_written: |
|
226 |
self.__writeheaders() |
|
227 |
f = open(filename) |
|
228 |
buf = f.read(1024) |
|
229 |
while len(buf) > 0: |
|
230 |
sys.stdout.write(buf) |
|
231 |
sys.stdout.flush() |
|
232 |
buf = f.read(1024) |
|
233 |
f.close() |
|
234 |
||
235 |
def read(self, len=None): |
|
236 |
"""Reads at most len bytes directly from the client. (See mod_python
|
|
237 |
Request.read)."""
|
|
238 |
if len is None: |
|
239 |
return sys.stdin.read() |
|
240 |
else: |
|
241 |
return sys.stdin.read(len) |
|
242 |
||
243 |
def handle_unknown_exception(self, exc_type, exc_value, exc_tb): |
|
244 |
if exc_type is ivle.util.IVLEError: |
|
245 |
self.headers_out['X-IVLE-Error-Code'] = exc_value.httpcode |
|
246 |
||
247 |
self.headers_out['X-IVLE-Error-Type'] = exc_type.__name__ |
|
248 |
||
249 |
try: |
|
250 |
self.headers_out['X-IVLE-Error-Message'] = exc_value.message |
|
251 |
except AttributeError: |
|
252 |
pass
|
|
253 |
||
254 |
self.headers_out['X-IVLE-Error-Info'] = urllib.quote(''.join( |
|
255 |
traceback.format_exception(exc_type, exc_value, exc_tb))) |
|
256 |
self.status = 500 |
|
257 |
self.ensure_headers_written() |
|
258 |
self.write('An internal IVLE error has occurred.') |
|
259 |
self.flush() |
|
260 |
sys.exit(self.status) |
|
261 |
||
262 |
def throw_redirect(self, location): |
|
263 |
"""Writes out an HTTP redirect to the specified URL. Exits the
|
|
264 |
process, so any code following this call will not be executed.
|
|
265 |
||
266 |
httpcode: An HTTP response status code. Pass a constant from the
|
|
267 |
Request class.
|
|
268 |
"""
|
|
269 |
self.status = CGIRequest.HTTP_MOVED_TEMPORARILY |
|
270 |
self.location = location |
|
271 |
self.ensure_headers_written() |
|
272 |
self.flush() |
|
273 |
sys.exit(self.status) |
|
274 |
||
275 |
def get_session(self): |
|
276 |
"""Returns a mod_python Session object for this request.
|
|
277 |
Note that this is dependent on mod_python and may need to change
|
|
278 |
interface if porting away from mod_python."""
|
|
279 |
# Cache the session object
|
|
280 |
if not hasattr(self, 'session'): |
|
281 |
#self.session = Session.FileSession(self.apache_req)
|
|
282 |
self.session = None |
|
283 |
# FIXME: How to get session?
|
|
284 |
return self.session |
|
285 |
||
286 |
def get_fieldstorage(self): |
|
287 |
"""Returns a mod_python FieldStorage object for this request.
|
|
288 |
Note that this is dependent on mod_python and may need to change
|
|
289 |
interface if porting away from mod_python."""
|
|
290 |
# Cache the fieldstorage object
|
|
291 |
if not hasattr(self, 'fields'): |
|
292 |
self.fields = cgi.FieldStorage() |
|
293 |
return self.fields |
|
294 |
||
295 |
def get_cgi_environ(self): |
|
296 |
"""Returns the CGI environment emulation for this request. (Calls
|
|
297 |
add_common_vars). The environment is returned as a mapping
|
|
298 |
compatible with os.environ."""
|
|
299 |
return os.environ |