handlers.py 21 KB

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