~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to lib/common/cgirequest.py

  • Committer: mattgiuca
  • Date: 2008-01-20 10:03:06 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:251
setup.py: Worked the "files to copy into jail" out into a separate list
instead of being expressed as code.
Still need to add some more dependencies to get matplotlib working.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
# NOTE: This object does not support write_html_head_foot (simply because we
29
 
# do not need it in its intended application: fileservice).
30
 
 
31
 
import sys
32
 
import os
33
 
import cgi
34
 
 
35
 
import conf
36
 
import common
37
 
import common.util
38
 
 
39
 
# Utility functions
40
 
 
41
 
def _http_headers_in_from_cgi():
42
 
    """Returns a dictionary of HTTP headers and their values, reading from the
43
 
    CGI environment."""
44
 
    d = {}
45
 
    for k in os.environ.keys():
46
 
        if k.startswith("HTTP_"):
47
 
            # Change the case - underscores become - and each word is
48
 
            # capitalised
49
 
            varname = '-'.join(map(lambda x: x[0:1] + x[1:].lower(),
50
 
                                k[5:].split('_')))
51
 
            d[varname] = os.environ[k]
52
 
    return d
53
 
 
54
 
class CGIRequest:
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.
58
 
    """
59
 
 
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.
64
 
    OK  = 0
65
 
 
66
 
    # HTTP status codes
67
 
 
68
 
    HTTP_CONTINUE                     = 100
69
 
    HTTP_SWITCHING_PROTOCOLS          = 101
70
 
    HTTP_PROCESSING                   = 102
71
 
    HTTP_OK                           = 200
72
 
    HTTP_CREATED                      = 201
73
 
    HTTP_ACCEPTED                     = 202
74
 
    HTTP_NON_AUTHORITATIVE            = 203
75
 
    HTTP_NO_CONTENT                   = 204
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
82
 
    HTTP_SEE_OTHER                    = 303
83
 
    HTTP_NOT_MODIFIED                 = 304
84
 
    HTTP_USE_PROXY                    = 305
85
 
    HTTP_TEMPORARY_REDIRECT           = 307
86
 
    HTTP_BAD_REQUEST                  = 400
87
 
    HTTP_UNAUTHORIZED                 = 401
88
 
    HTTP_PAYMENT_REQUIRED             = 402
89
 
    HTTP_FORBIDDEN                    = 403
90
 
    HTTP_NOT_FOUND                    = 404
91
 
    HTTP_METHOD_NOT_ALLOWED           = 405
92
 
    HTTP_NOT_ACCEPTABLE               = 406
93
 
    HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
94
 
    HTTP_REQUEST_TIME_OUT             = 408
95
 
    HTTP_CONFLICT                     = 409
96
 
    HTTP_GONE                         = 410
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
105
 
    HTTP_LOCKED                       = 423
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
116
 
 
117
 
    def __init__(self):
118
 
        """Builds an CGI Request object from the current CGI environment.
119
 
        This results in an object with all of the necessary methods and
120
 
        additional fields.
121
 
        """
122
 
        self.headers_written = False
123
 
 
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")
128
 
 
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
133
 
        else:
134
 
            self.publicmode = False
135
 
 
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)
142
 
        if self.publicmode:
143
 
            self.app = None
144
 
            self.path = path
145
 
        else:
146
 
            (self.app, self.path) = (common.util.split_path(path))
147
 
        self.user = None
148
 
        self.hostname = os.environ['SERVER_NAME']
149
 
        self.headers_in = _http_headers_in_from_cgi()
150
 
        self.headers_out = {}
151
 
 
152
 
        # Default values for the output members
153
 
        self.status = CGIRequest.HTTP_OK
154
 
        self.content_type = None        # Use Apache's default
155
 
        self.location = None
156
 
        self.title = None     # Will be set by dispatch before passing to app
157
 
        self.styles = []
158
 
        self.scripts = []
159
 
        self.write_html_head_foot = False
160
 
        self.got_common_vars = False
161
 
 
162
 
    def __writeheaders(self):
163
 
        """Writes out the HTTP and HTML headers before any real data is
164
 
        written."""
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']
170
 
 
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:
178
 
                # Just redirect
179
 
                return
180
 
            # Else: This is a Client Redirect with Document
181
 
            print "Status: %d" % self.status
182
 
            print "Content-Type: %s" % self.content_type
183
 
        else:
184
 
            # This is a Document response
185
 
            print "Content-Type: %s" % self.content_type
186
 
            print "Status: %d" % self.status
187
 
 
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)
192
 
 
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
198
 
        print
199
 
 
200
 
    def ensure_headers_written(self):
201
 
        """Writes out the HTTP and HTML headers if they haven't already been
202
 
        written."""
203
 
        if not self.headers_written:
204
 
            self.__writeheaders()
205
 
 
206
 
    def write(self, string, flush=1):
207
 
        """Writes string directly to the client, then flushes the buffer,
208
 
        unless flush is 0."""
209
 
 
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'))
216
 
        else:
217
 
            # 8-bit clean strings just get written directly.
218
 
            # This includes binary strings.
219
 
            sys.stdout.write(string)
220
 
 
221
 
    def flush(self):
222
 
        """Flushes the output buffer."""
223
 
        sys.stdout.flush()
224
 
 
225
 
    def sendfile(self, filename):
226
 
        """Sends the named file directly to the client."""
227
 
        if not self.headers_written:
228
 
            self.__writeheaders()
229
 
        f = open(filename)
230
 
        buf = f.read(1024)
231
 
        while len(buf) > 0:
232
 
            sys.stdout.write(buf)
233
 
            sys.stdout.flush()
234
 
            buf = f.read(1024)
235
 
        f.close()
236
 
 
237
 
    def read(self, len=None):
238
 
        """Reads at most len bytes directly from the client. (See mod_python
239
 
        Request.read)."""
240
 
        if len is None:
241
 
            return sys.stdin.read()
242
 
        else:
243
 
            return sys.stdin.read(len)
244
 
 
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.
248
 
 
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
251
 
        exception).
252
 
 
253
 
        httpcode: An HTTP response status code. Pass a constant from the
254
 
        Request class.
255
 
        """
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">
260
 
<html><head>
261
 
<title>%d Error</title>
262
 
</head><body>
263
 
<h1>Error</h1>
264
 
<p>A %d error was triggered by a CGI app.</p>
265
 
</body></html>
266
 
""" % (httpcode, httpcode))
267
 
        # Exit the process completely
268
 
        self.flush()
269
 
        sys.exit(httpcode)
270
 
 
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.
274
 
 
275
 
        httpcode: An HTTP response status code. Pass a constant from the
276
 
        Request class.
277
 
        """
278
 
        self.status = CGIRequest.HTTP_MOVED_TEMPORARILY
279
 
        self.location = location
280
 
        self.ensure_headers_written()
281
 
        self.flush()
282
 
        sys.exit(self.status)
283
 
 
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)
291
 
            self.session = None
292
 
            # FIXME: How to get session?
293
 
        return self.session
294
 
 
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()
302
 
        return self.fields
303
 
 
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."""
308
 
        return os.environ