jpayne@68
|
1 """Base classes for server/gateway implementations"""
|
jpayne@68
|
2
|
jpayne@68
|
3 from .util import FileWrapper, guess_scheme, is_hop_by_hop
|
jpayne@68
|
4 from .headers import Headers
|
jpayne@68
|
5
|
jpayne@68
|
6 import sys, os, time
|
jpayne@68
|
7
|
jpayne@68
|
8 __all__ = [
|
jpayne@68
|
9 'BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler',
|
jpayne@68
|
10 'IISCGIHandler', 'read_environ'
|
jpayne@68
|
11 ]
|
jpayne@68
|
12
|
jpayne@68
|
13 # Weekday and month names for HTTP date/time formatting; always English!
|
jpayne@68
|
14 _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
jpayne@68
|
15 _monthname = [None, # Dummy so we can use 1-based month numbers
|
jpayne@68
|
16 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
jpayne@68
|
17 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
jpayne@68
|
18
|
jpayne@68
|
19 def format_date_time(timestamp):
|
jpayne@68
|
20 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
|
jpayne@68
|
21 return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
|
jpayne@68
|
22 _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
|
jpayne@68
|
23 )
|
jpayne@68
|
24
|
jpayne@68
|
25 _is_request = {
|
jpayne@68
|
26 'SCRIPT_NAME', 'PATH_INFO', 'QUERY_STRING', 'REQUEST_METHOD', 'AUTH_TYPE',
|
jpayne@68
|
27 'CONTENT_TYPE', 'CONTENT_LENGTH', 'HTTPS', 'REMOTE_USER', 'REMOTE_IDENT',
|
jpayne@68
|
28 }.__contains__
|
jpayne@68
|
29
|
jpayne@68
|
30 def _needs_transcode(k):
|
jpayne@68
|
31 return _is_request(k) or k.startswith('HTTP_') or k.startswith('SSL_') \
|
jpayne@68
|
32 or (k.startswith('REDIRECT_') and _needs_transcode(k[9:]))
|
jpayne@68
|
33
|
jpayne@68
|
34 def read_environ():
|
jpayne@68
|
35 """Read environment, fixing HTTP variables"""
|
jpayne@68
|
36 enc = sys.getfilesystemencoding()
|
jpayne@68
|
37 esc = 'surrogateescape'
|
jpayne@68
|
38 try:
|
jpayne@68
|
39 ''.encode('utf-8', esc)
|
jpayne@68
|
40 except LookupError:
|
jpayne@68
|
41 esc = 'replace'
|
jpayne@68
|
42 environ = {}
|
jpayne@68
|
43
|
jpayne@68
|
44 # Take the basic environment from native-unicode os.environ. Attempt to
|
jpayne@68
|
45 # fix up the variables that come from the HTTP request to compensate for
|
jpayne@68
|
46 # the bytes->unicode decoding step that will already have taken place.
|
jpayne@68
|
47 for k, v in os.environ.items():
|
jpayne@68
|
48 if _needs_transcode(k):
|
jpayne@68
|
49
|
jpayne@68
|
50 # On win32, the os.environ is natively Unicode. Different servers
|
jpayne@68
|
51 # decode the request bytes using different encodings.
|
jpayne@68
|
52 if sys.platform == 'win32':
|
jpayne@68
|
53 software = os.environ.get('SERVER_SOFTWARE', '').lower()
|
jpayne@68
|
54
|
jpayne@68
|
55 # On IIS, the HTTP request will be decoded as UTF-8 as long
|
jpayne@68
|
56 # as the input is a valid UTF-8 sequence. Otherwise it is
|
jpayne@68
|
57 # decoded using the system code page (mbcs), with no way to
|
jpayne@68
|
58 # detect this has happened. Because UTF-8 is the more likely
|
jpayne@68
|
59 # encoding, and mbcs is inherently unreliable (an mbcs string
|
jpayne@68
|
60 # that happens to be valid UTF-8 will not be decoded as mbcs)
|
jpayne@68
|
61 # always recreate the original bytes as UTF-8.
|
jpayne@68
|
62 if software.startswith('microsoft-iis/'):
|
jpayne@68
|
63 v = v.encode('utf-8').decode('iso-8859-1')
|
jpayne@68
|
64
|
jpayne@68
|
65 # Apache mod_cgi writes bytes-as-unicode (as if ISO-8859-1) direct
|
jpayne@68
|
66 # to the Unicode environ. No modification needed.
|
jpayne@68
|
67 elif software.startswith('apache/'):
|
jpayne@68
|
68 pass
|
jpayne@68
|
69
|
jpayne@68
|
70 # Python 3's http.server.CGIHTTPRequestHandler decodes
|
jpayne@68
|
71 # using the urllib.unquote default of UTF-8, amongst other
|
jpayne@68
|
72 # issues.
|
jpayne@68
|
73 elif (
|
jpayne@68
|
74 software.startswith('simplehttp/')
|
jpayne@68
|
75 and 'python/3' in software
|
jpayne@68
|
76 ):
|
jpayne@68
|
77 v = v.encode('utf-8').decode('iso-8859-1')
|
jpayne@68
|
78
|
jpayne@68
|
79 # For other servers, guess that they have written bytes to
|
jpayne@68
|
80 # the environ using stdio byte-oriented interfaces, ending up
|
jpayne@68
|
81 # with the system code page.
|
jpayne@68
|
82 else:
|
jpayne@68
|
83 v = v.encode(enc, 'replace').decode('iso-8859-1')
|
jpayne@68
|
84
|
jpayne@68
|
85 # Recover bytes from unicode environ, using surrogate escapes
|
jpayne@68
|
86 # where available (Python 3.1+).
|
jpayne@68
|
87 else:
|
jpayne@68
|
88 v = v.encode(enc, esc).decode('iso-8859-1')
|
jpayne@68
|
89
|
jpayne@68
|
90 environ[k] = v
|
jpayne@68
|
91 return environ
|
jpayne@68
|
92
|
jpayne@68
|
93
|
jpayne@68
|
94 class BaseHandler:
|
jpayne@68
|
95 """Manage the invocation of a WSGI application"""
|
jpayne@68
|
96
|
jpayne@68
|
97 # Configuration parameters; can override per-subclass or per-instance
|
jpayne@68
|
98 wsgi_version = (1,0)
|
jpayne@68
|
99 wsgi_multithread = True
|
jpayne@68
|
100 wsgi_multiprocess = True
|
jpayne@68
|
101 wsgi_run_once = False
|
jpayne@68
|
102
|
jpayne@68
|
103 origin_server = True # We are transmitting direct to client
|
jpayne@68
|
104 http_version = "1.0" # Version that should be used for response
|
jpayne@68
|
105 server_software = None # String name of server software, if any
|
jpayne@68
|
106
|
jpayne@68
|
107 # os_environ is used to supply configuration from the OS environment:
|
jpayne@68
|
108 # by default it's a copy of 'os.environ' as of import time, but you can
|
jpayne@68
|
109 # override this in e.g. your __init__ method.
|
jpayne@68
|
110 os_environ= read_environ()
|
jpayne@68
|
111
|
jpayne@68
|
112 # Collaborator classes
|
jpayne@68
|
113 wsgi_file_wrapper = FileWrapper # set to None to disable
|
jpayne@68
|
114 headers_class = Headers # must be a Headers-like class
|
jpayne@68
|
115
|
jpayne@68
|
116 # Error handling (also per-subclass or per-instance)
|
jpayne@68
|
117 traceback_limit = None # Print entire traceback to self.get_stderr()
|
jpayne@68
|
118 error_status = "500 Internal Server Error"
|
jpayne@68
|
119 error_headers = [('Content-Type','text/plain')]
|
jpayne@68
|
120 error_body = b"A server error occurred. Please contact the administrator."
|
jpayne@68
|
121
|
jpayne@68
|
122 # State variables (don't mess with these)
|
jpayne@68
|
123 status = result = None
|
jpayne@68
|
124 headers_sent = False
|
jpayne@68
|
125 headers = None
|
jpayne@68
|
126 bytes_sent = 0
|
jpayne@68
|
127
|
jpayne@68
|
128 def run(self, application):
|
jpayne@68
|
129 """Invoke the application"""
|
jpayne@68
|
130 # Note to self: don't move the close()! Asynchronous servers shouldn't
|
jpayne@68
|
131 # call close() from finish_response(), so if you close() anywhere but
|
jpayne@68
|
132 # the double-error branch here, you'll break asynchronous servers by
|
jpayne@68
|
133 # prematurely closing. Async servers must return from 'run()' without
|
jpayne@68
|
134 # closing if there might still be output to iterate over.
|
jpayne@68
|
135 try:
|
jpayne@68
|
136 self.setup_environ()
|
jpayne@68
|
137 self.result = application(self.environ, self.start_response)
|
jpayne@68
|
138 self.finish_response()
|
jpayne@68
|
139 except (ConnectionAbortedError, BrokenPipeError, ConnectionResetError):
|
jpayne@68
|
140 # We expect the client to close the connection abruptly from time
|
jpayne@68
|
141 # to time.
|
jpayne@68
|
142 return
|
jpayne@68
|
143 except:
|
jpayne@68
|
144 try:
|
jpayne@68
|
145 self.handle_error()
|
jpayne@68
|
146 except:
|
jpayne@68
|
147 # If we get an error handling an error, just give up already!
|
jpayne@68
|
148 self.close()
|
jpayne@68
|
149 raise # ...and let the actual server figure it out.
|
jpayne@68
|
150
|
jpayne@68
|
151
|
jpayne@68
|
152 def setup_environ(self):
|
jpayne@68
|
153 """Set up the environment for one request"""
|
jpayne@68
|
154
|
jpayne@68
|
155 env = self.environ = self.os_environ.copy()
|
jpayne@68
|
156 self.add_cgi_vars()
|
jpayne@68
|
157
|
jpayne@68
|
158 env['wsgi.input'] = self.get_stdin()
|
jpayne@68
|
159 env['wsgi.errors'] = self.get_stderr()
|
jpayne@68
|
160 env['wsgi.version'] = self.wsgi_version
|
jpayne@68
|
161 env['wsgi.run_once'] = self.wsgi_run_once
|
jpayne@68
|
162 env['wsgi.url_scheme'] = self.get_scheme()
|
jpayne@68
|
163 env['wsgi.multithread'] = self.wsgi_multithread
|
jpayne@68
|
164 env['wsgi.multiprocess'] = self.wsgi_multiprocess
|
jpayne@68
|
165
|
jpayne@68
|
166 if self.wsgi_file_wrapper is not None:
|
jpayne@68
|
167 env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
|
jpayne@68
|
168
|
jpayne@68
|
169 if self.origin_server and self.server_software:
|
jpayne@68
|
170 env.setdefault('SERVER_SOFTWARE',self.server_software)
|
jpayne@68
|
171
|
jpayne@68
|
172
|
jpayne@68
|
173 def finish_response(self):
|
jpayne@68
|
174 """Send any iterable data, then close self and the iterable
|
jpayne@68
|
175
|
jpayne@68
|
176 Subclasses intended for use in asynchronous servers will
|
jpayne@68
|
177 want to redefine this method, such that it sets up callbacks
|
jpayne@68
|
178 in the event loop to iterate over the data, and to call
|
jpayne@68
|
179 'self.close()' once the response is finished.
|
jpayne@68
|
180 """
|
jpayne@68
|
181 try:
|
jpayne@68
|
182 if not self.result_is_file() or not self.sendfile():
|
jpayne@68
|
183 for data in self.result:
|
jpayne@68
|
184 self.write(data)
|
jpayne@68
|
185 self.finish_content()
|
jpayne@68
|
186 except:
|
jpayne@68
|
187 # Call close() on the iterable returned by the WSGI application
|
jpayne@68
|
188 # in case of an exception.
|
jpayne@68
|
189 if hasattr(self.result, 'close'):
|
jpayne@68
|
190 self.result.close()
|
jpayne@68
|
191 raise
|
jpayne@68
|
192 else:
|
jpayne@68
|
193 # We only call close() when no exception is raised, because it
|
jpayne@68
|
194 # will set status, result, headers, and environ fields to None.
|
jpayne@68
|
195 # See bpo-29183 for more details.
|
jpayne@68
|
196 self.close()
|
jpayne@68
|
197
|
jpayne@68
|
198
|
jpayne@68
|
199 def get_scheme(self):
|
jpayne@68
|
200 """Return the URL scheme being used"""
|
jpayne@68
|
201 return guess_scheme(self.environ)
|
jpayne@68
|
202
|
jpayne@68
|
203
|
jpayne@68
|
204 def set_content_length(self):
|
jpayne@68
|
205 """Compute Content-Length or switch to chunked encoding if possible"""
|
jpayne@68
|
206 try:
|
jpayne@68
|
207 blocks = len(self.result)
|
jpayne@68
|
208 except (TypeError,AttributeError,NotImplementedError):
|
jpayne@68
|
209 pass
|
jpayne@68
|
210 else:
|
jpayne@68
|
211 if blocks==1:
|
jpayne@68
|
212 self.headers['Content-Length'] = str(self.bytes_sent)
|
jpayne@68
|
213 return
|
jpayne@68
|
214 # XXX Try for chunked encoding if origin server and client is 1.1
|
jpayne@68
|
215
|
jpayne@68
|
216
|
jpayne@68
|
217 def cleanup_headers(self):
|
jpayne@68
|
218 """Make any necessary header changes or defaults
|
jpayne@68
|
219
|
jpayne@68
|
220 Subclasses can extend this to add other defaults.
|
jpayne@68
|
221 """
|
jpayne@68
|
222 if 'Content-Length' not in self.headers:
|
jpayne@68
|
223 self.set_content_length()
|
jpayne@68
|
224
|
jpayne@68
|
225 def start_response(self, status, headers,exc_info=None):
|
jpayne@68
|
226 """'start_response()' callable as specified by PEP 3333"""
|
jpayne@68
|
227
|
jpayne@68
|
228 if exc_info:
|
jpayne@68
|
229 try:
|
jpayne@68
|
230 if self.headers_sent:
|
jpayne@68
|
231 # Re-raise original exception if headers sent
|
jpayne@68
|
232 raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
|
jpayne@68
|
233 finally:
|
jpayne@68
|
234 exc_info = None # avoid dangling circular ref
|
jpayne@68
|
235 elif self.headers is not None:
|
jpayne@68
|
236 raise AssertionError("Headers already set!")
|
jpayne@68
|
237
|
jpayne@68
|
238 self.status = status
|
jpayne@68
|
239 self.headers = self.headers_class(headers)
|
jpayne@68
|
240 status = self._convert_string_type(status, "Status")
|
jpayne@68
|
241 assert len(status)>=4,"Status must be at least 4 characters"
|
jpayne@68
|
242 assert status[:3].isdigit(), "Status message must begin w/3-digit code"
|
jpayne@68
|
243 assert status[3]==" ", "Status message must have a space after code"
|
jpayne@68
|
244
|
jpayne@68
|
245 if __debug__:
|
jpayne@68
|
246 for name, val in headers:
|
jpayne@68
|
247 name = self._convert_string_type(name, "Header name")
|
jpayne@68
|
248 val = self._convert_string_type(val, "Header value")
|
jpayne@68
|
249 assert not is_hop_by_hop(name),\
|
jpayne@68
|
250 f"Hop-by-hop header, '{name}: {val}', not allowed"
|
jpayne@68
|
251
|
jpayne@68
|
252 return self.write
|
jpayne@68
|
253
|
jpayne@68
|
254 def _convert_string_type(self, value, title):
|
jpayne@68
|
255 """Convert/check value type."""
|
jpayne@68
|
256 if type(value) is str:
|
jpayne@68
|
257 return value
|
jpayne@68
|
258 raise AssertionError(
|
jpayne@68
|
259 "{0} must be of type str (got {1})".format(title, repr(value))
|
jpayne@68
|
260 )
|
jpayne@68
|
261
|
jpayne@68
|
262 def send_preamble(self):
|
jpayne@68
|
263 """Transmit version/status/date/server, via self._write()"""
|
jpayne@68
|
264 if self.origin_server:
|
jpayne@68
|
265 if self.client_is_modern():
|
jpayne@68
|
266 self._write(('HTTP/%s %s\r\n' % (self.http_version,self.status)).encode('iso-8859-1'))
|
jpayne@68
|
267 if 'Date' not in self.headers:
|
jpayne@68
|
268 self._write(
|
jpayne@68
|
269 ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
|
jpayne@68
|
270 )
|
jpayne@68
|
271 if self.server_software and 'Server' not in self.headers:
|
jpayne@68
|
272 self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1'))
|
jpayne@68
|
273 else:
|
jpayne@68
|
274 self._write(('Status: %s\r\n' % self.status).encode('iso-8859-1'))
|
jpayne@68
|
275
|
jpayne@68
|
276 def write(self, data):
|
jpayne@68
|
277 """'write()' callable as specified by PEP 3333"""
|
jpayne@68
|
278
|
jpayne@68
|
279 assert type(data) is bytes, \
|
jpayne@68
|
280 "write() argument must be a bytes instance"
|
jpayne@68
|
281
|
jpayne@68
|
282 if not self.status:
|
jpayne@68
|
283 raise AssertionError("write() before start_response()")
|
jpayne@68
|
284
|
jpayne@68
|
285 elif not self.headers_sent:
|
jpayne@68
|
286 # Before the first output, send the stored headers
|
jpayne@68
|
287 self.bytes_sent = len(data) # make sure we know content-length
|
jpayne@68
|
288 self.send_headers()
|
jpayne@68
|
289 else:
|
jpayne@68
|
290 self.bytes_sent += len(data)
|
jpayne@68
|
291
|
jpayne@68
|
292 # XXX check Content-Length and truncate if too many bytes written?
|
jpayne@68
|
293 self._write(data)
|
jpayne@68
|
294 self._flush()
|
jpayne@68
|
295
|
jpayne@68
|
296
|
jpayne@68
|
297 def sendfile(self):
|
jpayne@68
|
298 """Platform-specific file transmission
|
jpayne@68
|
299
|
jpayne@68
|
300 Override this method in subclasses to support platform-specific
|
jpayne@68
|
301 file transmission. It is only called if the application's
|
jpayne@68
|
302 return iterable ('self.result') is an instance of
|
jpayne@68
|
303 'self.wsgi_file_wrapper'.
|
jpayne@68
|
304
|
jpayne@68
|
305 This method should return a true value if it was able to actually
|
jpayne@68
|
306 transmit the wrapped file-like object using a platform-specific
|
jpayne@68
|
307 approach. It should return a false value if normal iteration
|
jpayne@68
|
308 should be used instead. An exception can be raised to indicate
|
jpayne@68
|
309 that transmission was attempted, but failed.
|
jpayne@68
|
310
|
jpayne@68
|
311 NOTE: this method should call 'self.send_headers()' if
|
jpayne@68
|
312 'self.headers_sent' is false and it is going to attempt direct
|
jpayne@68
|
313 transmission of the file.
|
jpayne@68
|
314 """
|
jpayne@68
|
315 return False # No platform-specific transmission by default
|
jpayne@68
|
316
|
jpayne@68
|
317
|
jpayne@68
|
318 def finish_content(self):
|
jpayne@68
|
319 """Ensure headers and content have both been sent"""
|
jpayne@68
|
320 if not self.headers_sent:
|
jpayne@68
|
321 # Only zero Content-Length if not set by the application (so
|
jpayne@68
|
322 # that HEAD requests can be satisfied properly, see #3839)
|
jpayne@68
|
323 self.headers.setdefault('Content-Length', "0")
|
jpayne@68
|
324 self.send_headers()
|
jpayne@68
|
325 else:
|
jpayne@68
|
326 pass # XXX check if content-length was too short?
|
jpayne@68
|
327
|
jpayne@68
|
328 def close(self):
|
jpayne@68
|
329 """Close the iterable (if needed) and reset all instance vars
|
jpayne@68
|
330
|
jpayne@68
|
331 Subclasses may want to also drop the client connection.
|
jpayne@68
|
332 """
|
jpayne@68
|
333 try:
|
jpayne@68
|
334 if hasattr(self.result,'close'):
|
jpayne@68
|
335 self.result.close()
|
jpayne@68
|
336 finally:
|
jpayne@68
|
337 self.result = self.headers = self.status = self.environ = None
|
jpayne@68
|
338 self.bytes_sent = 0; self.headers_sent = False
|
jpayne@68
|
339
|
jpayne@68
|
340
|
jpayne@68
|
341 def send_headers(self):
|
jpayne@68
|
342 """Transmit headers to the client, via self._write()"""
|
jpayne@68
|
343 self.cleanup_headers()
|
jpayne@68
|
344 self.headers_sent = True
|
jpayne@68
|
345 if not self.origin_server or self.client_is_modern():
|
jpayne@68
|
346 self.send_preamble()
|
jpayne@68
|
347 self._write(bytes(self.headers))
|
jpayne@68
|
348
|
jpayne@68
|
349
|
jpayne@68
|
350 def result_is_file(self):
|
jpayne@68
|
351 """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
|
jpayne@68
|
352 wrapper = self.wsgi_file_wrapper
|
jpayne@68
|
353 return wrapper is not None and isinstance(self.result,wrapper)
|
jpayne@68
|
354
|
jpayne@68
|
355
|
jpayne@68
|
356 def client_is_modern(self):
|
jpayne@68
|
357 """True if client can accept status and headers"""
|
jpayne@68
|
358 return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
|
jpayne@68
|
359
|
jpayne@68
|
360
|
jpayne@68
|
361 def log_exception(self,exc_info):
|
jpayne@68
|
362 """Log the 'exc_info' tuple in the server log
|
jpayne@68
|
363
|
jpayne@68
|
364 Subclasses may override to retarget the output or change its format.
|
jpayne@68
|
365 """
|
jpayne@68
|
366 try:
|
jpayne@68
|
367 from traceback import print_exception
|
jpayne@68
|
368 stderr = self.get_stderr()
|
jpayne@68
|
369 print_exception(
|
jpayne@68
|
370 exc_info[0], exc_info[1], exc_info[2],
|
jpayne@68
|
371 self.traceback_limit, stderr
|
jpayne@68
|
372 )
|
jpayne@68
|
373 stderr.flush()
|
jpayne@68
|
374 finally:
|
jpayne@68
|
375 exc_info = None
|
jpayne@68
|
376
|
jpayne@68
|
377 def handle_error(self):
|
jpayne@68
|
378 """Log current error, and send error output to client if possible"""
|
jpayne@68
|
379 self.log_exception(sys.exc_info())
|
jpayne@68
|
380 if not self.headers_sent:
|
jpayne@68
|
381 self.result = self.error_output(self.environ, self.start_response)
|
jpayne@68
|
382 self.finish_response()
|
jpayne@68
|
383 # XXX else: attempt advanced recovery techniques for HTML or text?
|
jpayne@68
|
384
|
jpayne@68
|
385 def error_output(self, environ, start_response):
|
jpayne@68
|
386 """WSGI mini-app to create error output
|
jpayne@68
|
387
|
jpayne@68
|
388 By default, this just uses the 'error_status', 'error_headers',
|
jpayne@68
|
389 and 'error_body' attributes to generate an output page. It can
|
jpayne@68
|
390 be overridden in a subclass to dynamically generate diagnostics,
|
jpayne@68
|
391 choose an appropriate message for the user's preferred language, etc.
|
jpayne@68
|
392
|
jpayne@68
|
393 Note, however, that it's not recommended from a security perspective to
|
jpayne@68
|
394 spit out diagnostics to any old user; ideally, you should have to do
|
jpayne@68
|
395 something special to enable diagnostic output, which is why we don't
|
jpayne@68
|
396 include any here!
|
jpayne@68
|
397 """
|
jpayne@68
|
398 start_response(self.error_status,self.error_headers[:],sys.exc_info())
|
jpayne@68
|
399 return [self.error_body]
|
jpayne@68
|
400
|
jpayne@68
|
401
|
jpayne@68
|
402 # Pure abstract methods; *must* be overridden in subclasses
|
jpayne@68
|
403
|
jpayne@68
|
404 def _write(self,data):
|
jpayne@68
|
405 """Override in subclass to buffer data for send to client
|
jpayne@68
|
406
|
jpayne@68
|
407 It's okay if this method actually transmits the data; BaseHandler
|
jpayne@68
|
408 just separates write and flush operations for greater efficiency
|
jpayne@68
|
409 when the underlying system actually has such a distinction.
|
jpayne@68
|
410 """
|
jpayne@68
|
411 raise NotImplementedError
|
jpayne@68
|
412
|
jpayne@68
|
413 def _flush(self):
|
jpayne@68
|
414 """Override in subclass to force sending of recent '_write()' calls
|
jpayne@68
|
415
|
jpayne@68
|
416 It's okay if this method is a no-op (i.e., if '_write()' actually
|
jpayne@68
|
417 sends the data.
|
jpayne@68
|
418 """
|
jpayne@68
|
419 raise NotImplementedError
|
jpayne@68
|
420
|
jpayne@68
|
421 def get_stdin(self):
|
jpayne@68
|
422 """Override in subclass to return suitable 'wsgi.input'"""
|
jpayne@68
|
423 raise NotImplementedError
|
jpayne@68
|
424
|
jpayne@68
|
425 def get_stderr(self):
|
jpayne@68
|
426 """Override in subclass to return suitable 'wsgi.errors'"""
|
jpayne@68
|
427 raise NotImplementedError
|
jpayne@68
|
428
|
jpayne@68
|
429 def add_cgi_vars(self):
|
jpayne@68
|
430 """Override in subclass to insert CGI variables in 'self.environ'"""
|
jpayne@68
|
431 raise NotImplementedError
|
jpayne@68
|
432
|
jpayne@68
|
433
|
jpayne@68
|
434 class SimpleHandler(BaseHandler):
|
jpayne@68
|
435 """Handler that's just initialized with streams, environment, etc.
|
jpayne@68
|
436
|
jpayne@68
|
437 This handler subclass is intended for synchronous HTTP/1.0 origin servers,
|
jpayne@68
|
438 and handles sending the entire response output, given the correct inputs.
|
jpayne@68
|
439
|
jpayne@68
|
440 Usage::
|
jpayne@68
|
441
|
jpayne@68
|
442 handler = SimpleHandler(
|
jpayne@68
|
443 inp,out,err,env, multithread=False, multiprocess=True
|
jpayne@68
|
444 )
|
jpayne@68
|
445 handler.run(app)"""
|
jpayne@68
|
446
|
jpayne@68
|
447 def __init__(self,stdin,stdout,stderr,environ,
|
jpayne@68
|
448 multithread=True, multiprocess=False
|
jpayne@68
|
449 ):
|
jpayne@68
|
450 self.stdin = stdin
|
jpayne@68
|
451 self.stdout = stdout
|
jpayne@68
|
452 self.stderr = stderr
|
jpayne@68
|
453 self.base_env = environ
|
jpayne@68
|
454 self.wsgi_multithread = multithread
|
jpayne@68
|
455 self.wsgi_multiprocess = multiprocess
|
jpayne@68
|
456
|
jpayne@68
|
457 def get_stdin(self):
|
jpayne@68
|
458 return self.stdin
|
jpayne@68
|
459
|
jpayne@68
|
460 def get_stderr(self):
|
jpayne@68
|
461 return self.stderr
|
jpayne@68
|
462
|
jpayne@68
|
463 def add_cgi_vars(self):
|
jpayne@68
|
464 self.environ.update(self.base_env)
|
jpayne@68
|
465
|
jpayne@68
|
466 def _write(self,data):
|
jpayne@68
|
467 result = self.stdout.write(data)
|
jpayne@68
|
468 if result is None or result == len(data):
|
jpayne@68
|
469 return
|
jpayne@68
|
470 from warnings import warn
|
jpayne@68
|
471 warn("SimpleHandler.stdout.write() should not do partial writes",
|
jpayne@68
|
472 DeprecationWarning)
|
jpayne@68
|
473 while True:
|
jpayne@68
|
474 data = data[result:]
|
jpayne@68
|
475 if not data:
|
jpayne@68
|
476 break
|
jpayne@68
|
477 result = self.stdout.write(data)
|
jpayne@68
|
478
|
jpayne@68
|
479 def _flush(self):
|
jpayne@68
|
480 self.stdout.flush()
|
jpayne@68
|
481 self._flush = self.stdout.flush
|
jpayne@68
|
482
|
jpayne@68
|
483
|
jpayne@68
|
484 class BaseCGIHandler(SimpleHandler):
|
jpayne@68
|
485
|
jpayne@68
|
486 """CGI-like systems using input/output/error streams and environ mapping
|
jpayne@68
|
487
|
jpayne@68
|
488 Usage::
|
jpayne@68
|
489
|
jpayne@68
|
490 handler = BaseCGIHandler(inp,out,err,env)
|
jpayne@68
|
491 handler.run(app)
|
jpayne@68
|
492
|
jpayne@68
|
493 This handler class is useful for gateway protocols like ReadyExec and
|
jpayne@68
|
494 FastCGI, that have usable input/output/error streams and an environment
|
jpayne@68
|
495 mapping. It's also the base class for CGIHandler, which just uses
|
jpayne@68
|
496 sys.stdin, os.environ, and so on.
|
jpayne@68
|
497
|
jpayne@68
|
498 The constructor also takes keyword arguments 'multithread' and
|
jpayne@68
|
499 'multiprocess' (defaulting to 'True' and 'False' respectively) to control
|
jpayne@68
|
500 the configuration sent to the application. It sets 'origin_server' to
|
jpayne@68
|
501 False (to enable CGI-like output), and assumes that 'wsgi.run_once' is
|
jpayne@68
|
502 False.
|
jpayne@68
|
503 """
|
jpayne@68
|
504
|
jpayne@68
|
505 origin_server = False
|
jpayne@68
|
506
|
jpayne@68
|
507
|
jpayne@68
|
508 class CGIHandler(BaseCGIHandler):
|
jpayne@68
|
509
|
jpayne@68
|
510 """CGI-based invocation via sys.stdin/stdout/stderr and os.environ
|
jpayne@68
|
511
|
jpayne@68
|
512 Usage::
|
jpayne@68
|
513
|
jpayne@68
|
514 CGIHandler().run(app)
|
jpayne@68
|
515
|
jpayne@68
|
516 The difference between this class and BaseCGIHandler is that it always
|
jpayne@68
|
517 uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and
|
jpayne@68
|
518 'wsgi.multiprocess' of 'True'. It does not take any initialization
|
jpayne@68
|
519 parameters, but always uses 'sys.stdin', 'os.environ', and friends.
|
jpayne@68
|
520
|
jpayne@68
|
521 If you need to override any of these parameters, use BaseCGIHandler
|
jpayne@68
|
522 instead.
|
jpayne@68
|
523 """
|
jpayne@68
|
524
|
jpayne@68
|
525 wsgi_run_once = True
|
jpayne@68
|
526 # Do not allow os.environ to leak between requests in Google App Engine
|
jpayne@68
|
527 # and other multi-run CGI use cases. This is not easily testable.
|
jpayne@68
|
528 # See http://bugs.python.org/issue7250
|
jpayne@68
|
529 os_environ = {}
|
jpayne@68
|
530
|
jpayne@68
|
531 def __init__(self):
|
jpayne@68
|
532 BaseCGIHandler.__init__(
|
jpayne@68
|
533 self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr,
|
jpayne@68
|
534 read_environ(), multithread=False, multiprocess=True
|
jpayne@68
|
535 )
|
jpayne@68
|
536
|
jpayne@68
|
537
|
jpayne@68
|
538 class IISCGIHandler(BaseCGIHandler):
|
jpayne@68
|
539 """CGI-based invocation with workaround for IIS path bug
|
jpayne@68
|
540
|
jpayne@68
|
541 This handler should be used in preference to CGIHandler when deploying on
|
jpayne@68
|
542 Microsoft IIS without having set the config allowPathInfo option (IIS>=7)
|
jpayne@68
|
543 or metabase allowPathInfoForScriptMappings (IIS<7).
|
jpayne@68
|
544 """
|
jpayne@68
|
545 wsgi_run_once = True
|
jpayne@68
|
546 os_environ = {}
|
jpayne@68
|
547
|
jpayne@68
|
548 # By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at
|
jpayne@68
|
549 # the front, causing problems for WSGI applications that wish to implement
|
jpayne@68
|
550 # routing. This handler strips any such duplicated path.
|
jpayne@68
|
551
|
jpayne@68
|
552 # IIS can be configured to pass the correct PATH_INFO, but this causes
|
jpayne@68
|
553 # another bug where PATH_TRANSLATED is wrong. Luckily this variable is
|
jpayne@68
|
554 # rarely used and is not guaranteed by WSGI. On IIS<7, though, the
|
jpayne@68
|
555 # setting can only be made on a vhost level, affecting all other script
|
jpayne@68
|
556 # mappings, many of which break when exposed to the PATH_TRANSLATED bug.
|
jpayne@68
|
557 # For this reason IIS<7 is almost never deployed with the fix. (Even IIS7
|
jpayne@68
|
558 # rarely uses it because there is still no UI for it.)
|
jpayne@68
|
559
|
jpayne@68
|
560 # There is no way for CGI code to tell whether the option was set, so a
|
jpayne@68
|
561 # separate handler class is provided.
|
jpayne@68
|
562 def __init__(self):
|
jpayne@68
|
563 environ= read_environ()
|
jpayne@68
|
564 path = environ.get('PATH_INFO', '')
|
jpayne@68
|
565 script = environ.get('SCRIPT_NAME', '')
|
jpayne@68
|
566 if (path+'/').startswith(script+'/'):
|
jpayne@68
|
567 environ['PATH_INFO'] = path[len(script):]
|
jpayne@68
|
568 BaseCGIHandler.__init__(
|
jpayne@68
|
569 self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr,
|
jpayne@68
|
570 environ, multithread=False, multiprocess=True
|
jpayne@68
|
571 )
|