handlers.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """Base classes for server/gateway implementations"""
  2. from types import StringType
  3. from util import FileWrapper, guess_scheme, is_hop_by_hop
  4. from headers import Headers
  5. import sys, os, time
  6. __all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
  7. try:
  8. dict
  9. except NameError:
  10. def dict(items):
  11. d = {}
  12. for k,v in items:
  13. d[k] = v
  14. return d
  15. # Uncomment for 2.2 compatibility.
  16. #try:
  17. # True
  18. # False
  19. #except NameError:
  20. # True = not None
  21. # False = not True
  22. # Weekday and month names for HTTP date/time formatting; always English!
  23. _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  24. _monthname = [None, # Dummy so we can use 1-based month numbers
  25. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  26. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  27. def format_date_time(timestamp):
  28. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  29. return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  30. _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
  31. )
  32. class BaseHandler:
  33. """Manage the invocation of a WSGI application"""
  34. # Configuration parameters; can override per-subclass or per-instance
  35. wsgi_version = (1,0)
  36. wsgi_multithread = True
  37. wsgi_multiprocess = True
  38. wsgi_run_once = False
  39. origin_server = True # We are transmitting direct to client
  40. http_version = "1.0" # Version that should be used for response
  41. server_software = None # String name of server software, if any
  42. # os_environ is used to supply configuration from the OS environment:
  43. # by default it's a copy of 'os.environ' as of import time, but you can
  44. # override this in e.g. your __init__ method.
  45. os_environ = dict(os.environ.items())
  46. # Collaborator classes
  47. wsgi_file_wrapper = FileWrapper # set to None to disable
  48. headers_class = Headers # must be a Headers-like class
  49. # Error handling (also per-subclass or per-instance)
  50. traceback_limit = None # Print entire traceback to self.get_stderr()
  51. error_status = "500 Internal Server Error"
  52. error_headers = [('Content-Type','text/plain')]
  53. error_body = "A server error occurred. Please contact the administrator."
  54. # State variables (don't mess with these)
  55. status = result = None
  56. headers_sent = False
  57. headers = None
  58. bytes_sent = 0
  59. def run(self, application):
  60. """Invoke the application"""
  61. # Note to self: don't move the close()! Asynchronous servers shouldn't
  62. # call close() from finish_response(), so if you close() anywhere but
  63. # the double-error branch here, you'll break asynchronous servers by
  64. # prematurely closing. Async servers must return from 'run()' without
  65. # closing if there might still be output to iterate over.
  66. try:
  67. self.setup_environ()
  68. self.result = application(self.environ, self.start_response)
  69. self.finish_response()
  70. except:
  71. try:
  72. self.handle_error()
  73. except:
  74. # If we get an error handling an error, just give up already!
  75. self.close()
  76. raise # ...and let the actual server figure it out.
  77. def setup_environ(self):
  78. """Set up the environment for one request"""
  79. env = self.environ = self.os_environ.copy()
  80. self.add_cgi_vars()
  81. env['wsgi.input'] = self.get_stdin()
  82. env['wsgi.errors'] = self.get_stderr()
  83. env['wsgi.version'] = self.wsgi_version
  84. env['wsgi.run_once'] = self.wsgi_run_once
  85. env['wsgi.url_scheme'] = self.get_scheme()
  86. env['wsgi.multithread'] = self.wsgi_multithread
  87. env['wsgi.multiprocess'] = self.wsgi_multiprocess
  88. if self.wsgi_file_wrapper is not None:
  89. env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
  90. if self.origin_server and self.server_software:
  91. env.setdefault('SERVER_SOFTWARE',self.server_software)
  92. def finish_response(self):
  93. """Send any iterable data, then close self and the iterable
  94. Subclasses intended for use in asynchronous servers will
  95. want to redefine this method, such that it sets up callbacks
  96. in the event loop to iterate over the data, and to call
  97. 'self.close()' once the response is finished.
  98. """
  99. try:
  100. if not self.result_is_file() or not self.sendfile():
  101. for data in self.result:
  102. self.write(data)
  103. self.finish_content()
  104. finally:
  105. self.close()
  106. def get_scheme(self):
  107. """Return the URL scheme being used"""
  108. return guess_scheme(self.environ)
  109. def set_content_length(self):
  110. """Compute Content-Length or switch to chunked encoding if possible"""
  111. try:
  112. blocks = len(self.result)
  113. except (TypeError,AttributeError,NotImplementedError):
  114. pass
  115. else:
  116. if blocks==1:
  117. self.headers['Content-Length'] = str(self.bytes_sent)
  118. return
  119. # XXX Try for chunked encoding if origin server and client is 1.1
  120. def cleanup_headers(self):
  121. """Make any necessary header changes or defaults
  122. Subclasses can extend this to add other defaults.
  123. """
  124. if 'Content-Length' not in self.headers:
  125. self.set_content_length()
  126. def start_response(self, status, headers,exc_info=None):
  127. """'start_response()' callable as specified by PEP 333"""
  128. if exc_info:
  129. try:
  130. if self.headers_sent:
  131. # Re-raise original exception if headers sent
  132. raise exc_info[0], exc_info[1], exc_info[2]
  133. finally:
  134. exc_info = None # avoid dangling circular ref
  135. elif self.headers is not None:
  136. raise AssertionError("Headers already set!")
  137. assert type(status) is StringType,"Status must be a string"
  138. assert len(status)>=4,"Status must be at least 4 characters"
  139. assert int(status[:3]),"Status message must begin w/3-digit code"
  140. assert status[3]==" ", "Status message must have a space after code"
  141. if __debug__:
  142. for name,val in headers:
  143. assert type(name) is StringType,"Header names must be strings"
  144. assert type(val) is StringType,"Header values must be strings"
  145. assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
  146. self.status = status
  147. self.headers = self.headers_class(headers)
  148. return self.write
  149. def send_preamble(self):
  150. """Transmit version/status/date/server, via self._write()"""
  151. if self.origin_server:
  152. if self.client_is_modern():
  153. self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
  154. if 'Date' not in self.headers:
  155. self._write(
  156. 'Date: %s\r\n' % format_date_time(time.time())
  157. )
  158. if self.server_software and 'Server' not in self.headers:
  159. self._write('Server: %s\r\n' % self.server_software)
  160. else:
  161. self._write('Status: %s\r\n' % self.status)
  162. def write(self, data):
  163. """'write()' callable as specified by PEP 333"""
  164. assert type(data) is StringType,"write() argument must be string"
  165. if not self.status:
  166. raise AssertionError("write() before start_response()")
  167. elif not self.headers_sent:
  168. # Before the first output, send the stored headers
  169. self.bytes_sent = len(data) # make sure we know content-length
  170. self.send_headers()
  171. else:
  172. self.bytes_sent += len(data)
  173. # XXX check Content-Length and truncate if too many bytes written?
  174. self._write(data)
  175. self._flush()
  176. def sendfile(self):
  177. """Platform-specific file transmission
  178. Override this method in subclasses to support platform-specific
  179. file transmission. It is only called if the application's
  180. return iterable ('self.result') is an instance of
  181. 'self.wsgi_file_wrapper'.
  182. This method should return a true value if it was able to actually
  183. transmit the wrapped file-like object using a platform-specific
  184. approach. It should return a false value if normal iteration
  185. should be used instead. An exception can be raised to indicate
  186. that transmission was attempted, but failed.
  187. NOTE: this method should call 'self.send_headers()' if
  188. 'self.headers_sent' is false and it is going to attempt direct
  189. transmission of the file.
  190. """
  191. return False # No platform-specific transmission by default
  192. def finish_content(self):
  193. """Ensure headers and content have both been sent"""
  194. if not self.headers_sent:
  195. # Only zero Content-Length if not set by the application (so
  196. # that HEAD requests can be satisfied properly, see #3839)
  197. self.headers.setdefault('Content-Length', "0")
  198. self.send_headers()
  199. else:
  200. pass # XXX check if content-length was too short?
  201. def close(self):
  202. """Close the iterable (if needed) and reset all instance vars
  203. Subclasses may want to also drop the client connection.
  204. """
  205. try:
  206. if hasattr(self.result,'close'):
  207. self.result.close()
  208. finally:
  209. self.result = self.headers = self.status = self.environ = None
  210. self.bytes_sent = 0; self.headers_sent = False
  211. def send_headers(self):
  212. """Transmit headers to the client, via self._write()"""
  213. self.cleanup_headers()
  214. self.headers_sent = True
  215. if not self.origin_server or self.client_is_modern():
  216. self.send_preamble()
  217. self._write(str(self.headers))
  218. def result_is_file(self):
  219. """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
  220. wrapper = self.wsgi_file_wrapper
  221. return wrapper is not None and isinstance(self.result,wrapper)
  222. def client_is_modern(self):
  223. """True if client can accept status and headers"""
  224. return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
  225. def log_exception(self,exc_info):
  226. """Log the 'exc_info' tuple in the server log
  227. Subclasses may override to retarget the output or change its format.
  228. """
  229. try:
  230. from traceback import print_exception
  231. stderr = self.get_stderr()
  232. print_exception(
  233. exc_info[0], exc_info[1], exc_info[2],
  234. self.traceback_limit, stderr
  235. )
  236. stderr.flush()
  237. finally:
  238. exc_info = None
  239. def handle_error(self):
  240. """Log current error, and send error output to client if possible"""
  241. self.log_exception(sys.exc_info())
  242. if not self.headers_sent:
  243. self.result = self.error_output(self.environ, self.start_response)
  244. self.finish_response()
  245. # XXX else: attempt advanced recovery techniques for HTML or text?
  246. def error_output(self, environ, start_response):
  247. """WSGI mini-app to create error output
  248. By default, this just uses the 'error_status', 'error_headers',
  249. and 'error_body' attributes to generate an output page. It can
  250. be overridden in a subclass to dynamically generate diagnostics,
  251. choose an appropriate message for the user's preferred language, etc.
  252. Note, however, that it's not recommended from a security perspective to
  253. spit out diagnostics to any old user; ideally, you should have to do
  254. something special to enable diagnostic output, which is why we don't
  255. include any here!
  256. """
  257. start_response(self.error_status,self.error_headers[:],sys.exc_info())
  258. return [self.error_body]
  259. # Pure abstract methods; *must* be overridden in subclasses
  260. def _write(self,data):
  261. """Override in subclass to buffer data for send to client
  262. It's okay if this method actually transmits the data; BaseHandler
  263. just separates write and flush operations for greater efficiency
  264. when the underlying system actually has such a distinction.
  265. """
  266. raise NotImplementedError
  267. def _flush(self):
  268. """Override in subclass to force sending of recent '_write()' calls
  269. It's okay if this method is a no-op (i.e., if '_write()' actually
  270. sends the data.
  271. """
  272. raise NotImplementedError
  273. def get_stdin(self):
  274. """Override in subclass to return suitable 'wsgi.input'"""
  275. raise NotImplementedError
  276. def get_stderr(self):
  277. """Override in subclass to return suitable 'wsgi.errors'"""
  278. raise NotImplementedError
  279. def add_cgi_vars(self):
  280. """Override in subclass to insert CGI variables in 'self.environ'"""
  281. raise NotImplementedError
  282. class SimpleHandler(BaseHandler):
  283. """Handler that's just initialized with streams, environment, etc.
  284. This handler subclass is intended for synchronous HTTP/1.0 origin servers,
  285. and handles sending the entire response output, given the correct inputs.
  286. Usage::
  287. handler = SimpleHandler(
  288. inp,out,err,env, multithread=False, multiprocess=True
  289. )
  290. handler.run(app)"""
  291. def __init__(self,stdin,stdout,stderr,environ,
  292. multithread=True, multiprocess=False
  293. ):
  294. self.stdin = stdin
  295. self.stdout = stdout
  296. self.stderr = stderr
  297. self.base_env = environ
  298. self.wsgi_multithread = multithread
  299. self.wsgi_multiprocess = multiprocess
  300. def get_stdin(self):
  301. return self.stdin
  302. def get_stderr(self):
  303. return self.stderr
  304. def add_cgi_vars(self):
  305. self.environ.update(self.base_env)
  306. def _write(self,data):
  307. self.stdout.write(data)
  308. self._write = self.stdout.write
  309. def _flush(self):
  310. self.stdout.flush()
  311. self._flush = self.stdout.flush
  312. class BaseCGIHandler(SimpleHandler):
  313. """CGI-like systems using input/output/error streams and environ mapping
  314. Usage::
  315. handler = BaseCGIHandler(inp,out,err,env)
  316. handler.run(app)
  317. This handler class is useful for gateway protocols like ReadyExec and
  318. FastCGI, that have usable input/output/error streams and an environment
  319. mapping. It's also the base class for CGIHandler, which just uses
  320. sys.stdin, os.environ, and so on.
  321. The constructor also takes keyword arguments 'multithread' and
  322. 'multiprocess' (defaulting to 'True' and 'False' respectively) to control
  323. the configuration sent to the application. It sets 'origin_server' to
  324. False (to enable CGI-like output), and assumes that 'wsgi.run_once' is
  325. False.
  326. """
  327. origin_server = False
  328. class CGIHandler(BaseCGIHandler):
  329. """CGI-based invocation via sys.stdin/stdout/stderr and os.environ
  330. Usage::
  331. CGIHandler().run(app)
  332. The difference between this class and BaseCGIHandler is that it always
  333. uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and
  334. 'wsgi.multiprocess' of 'True'. It does not take any initialization
  335. parameters, but always uses 'sys.stdin', 'os.environ', and friends.
  336. If you need to override any of these parameters, use BaseCGIHandler
  337. instead.
  338. """
  339. wsgi_run_once = True
  340. # Do not allow os.environ to leak between requests in Google App Engine
  341. # and other multi-run CGI use cases. This is not easily testable.
  342. # See http://bugs.python.org/issue7250
  343. os_environ = {}
  344. def __init__(self):
  345. BaseCGIHandler.__init__(
  346. self, sys.stdin, sys.stdout, sys.stderr, dict(os.environ.items()),
  347. multithread=False, multiprocess=True
  348. )