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