handlers.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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 (ConnectionAbortedError, BrokenPipeError, ConnectionResetError):
  115. # We expect the client to close the connection abruptly from time
  116. # to time.
  117. return
  118. except:
  119. try:
  120. self.handle_error()
  121. except:
  122. # If we get an error handling an error, just give up already!
  123. self.close()
  124. raise # ...and let the actual server figure it out.
  125. def setup_environ(self):
  126. """Set up the environment for one request"""
  127. env = self.environ = self.os_environ.copy()
  128. self.add_cgi_vars()
  129. env['wsgi.input'] = self.get_stdin()
  130. env['wsgi.errors'] = self.get_stderr()
  131. env['wsgi.version'] = self.wsgi_version
  132. env['wsgi.run_once'] = self.wsgi_run_once
  133. env['wsgi.url_scheme'] = self.get_scheme()
  134. env['wsgi.multithread'] = self.wsgi_multithread
  135. env['wsgi.multiprocess'] = self.wsgi_multiprocess
  136. if self.wsgi_file_wrapper is not None:
  137. env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
  138. if self.origin_server and self.server_software:
  139. env.setdefault('SERVER_SOFTWARE',self.server_software)
  140. def finish_response(self):
  141. """Send any iterable data, then close self and the iterable
  142. Subclasses intended for use in asynchronous servers will
  143. want to redefine this method, such that it sets up callbacks
  144. in the event loop to iterate over the data, and to call
  145. 'self.close()' once the response is finished.
  146. """
  147. try:
  148. if not self.result_is_file() or not self.sendfile():
  149. for data in self.result:
  150. self.write(data)
  151. self.finish_content()
  152. except:
  153. # Call close() on the iterable returned by the WSGI application
  154. # in case of an exception.
  155. if hasattr(self.result, 'close'):
  156. self.result.close()
  157. raise
  158. else:
  159. # We only call close() when no exception is raised, because it
  160. # will set status, result, headers, and environ fields to None.
  161. # See bpo-29183 for more details.
  162. self.close()
  163. def get_scheme(self):
  164. """Return the URL scheme being used"""
  165. return guess_scheme(self.environ)
  166. def set_content_length(self):
  167. """Compute Content-Length or switch to chunked encoding if possible"""
  168. try:
  169. blocks = len(self.result)
  170. except (TypeError,AttributeError,NotImplementedError):
  171. pass
  172. else:
  173. if blocks==1:
  174. self.headers['Content-Length'] = str(self.bytes_sent)
  175. return
  176. # XXX Try for chunked encoding if origin server and client is 1.1
  177. def cleanup_headers(self):
  178. """Make any necessary header changes or defaults
  179. Subclasses can extend this to add other defaults.
  180. """
  181. if 'Content-Length' not in self.headers:
  182. self.set_content_length()
  183. def start_response(self, status, headers,exc_info=None):
  184. """'start_response()' callable as specified by PEP 3333"""
  185. if exc_info:
  186. try:
  187. if self.headers_sent:
  188. # Re-raise original exception if headers sent
  189. raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
  190. finally:
  191. exc_info = None # avoid dangling circular ref
  192. elif self.headers is not None:
  193. raise AssertionError("Headers already set!")
  194. self.status = status
  195. self.headers = self.headers_class(headers)
  196. status = self._convert_string_type(status, "Status")
  197. assert len(status)>=4,"Status must be at least 4 characters"
  198. assert status[:3].isdigit(), "Status message must begin w/3-digit code"
  199. assert status[3]==" ", "Status message must have a space after code"
  200. if __debug__:
  201. for name, val in headers:
  202. name = self._convert_string_type(name, "Header name")
  203. val = self._convert_string_type(val, "Header value")
  204. assert not is_hop_by_hop(name),\
  205. f"Hop-by-hop header, '{name}: {val}', not allowed"
  206. return self.write
  207. def _convert_string_type(self, value, title):
  208. """Convert/check value type."""
  209. if type(value) is str:
  210. return value
  211. raise AssertionError(
  212. "{0} must be of type str (got {1})".format(title, repr(value))
  213. )
  214. def send_preamble(self):
  215. """Transmit version/status/date/server, via self._write()"""
  216. if self.origin_server:
  217. if self.client_is_modern():
  218. self._write(('HTTP/%s %s\r\n' % (self.http_version,self.status)).encode('iso-8859-1'))
  219. if 'Date' not in self.headers:
  220. self._write(
  221. ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  222. )
  223. if self.server_software and 'Server' not in self.headers:
  224. self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1'))
  225. else:
  226. self._write(('Status: %s\r\n' % self.status).encode('iso-8859-1'))
  227. def write(self, data):
  228. """'write()' callable as specified by PEP 3333"""
  229. assert type(data) is bytes, \
  230. "write() argument must be a bytes instance"
  231. if not self.status:
  232. raise AssertionError("write() before start_response()")
  233. elif not self.headers_sent:
  234. # Before the first output, send the stored headers
  235. self.bytes_sent = len(data) # make sure we know content-length
  236. self.send_headers()
  237. else:
  238. self.bytes_sent += len(data)
  239. # XXX check Content-Length and truncate if too many bytes written?
  240. self._write(data)
  241. self._flush()
  242. def sendfile(self):
  243. """Platform-specific file transmission
  244. Override this method in subclasses to support platform-specific
  245. file transmission. It is only called if the application's
  246. return iterable ('self.result') is an instance of
  247. 'self.wsgi_file_wrapper'.
  248. This method should return a true value if it was able to actually
  249. transmit the wrapped file-like object using a platform-specific
  250. approach. It should return a false value if normal iteration
  251. should be used instead. An exception can be raised to indicate
  252. that transmission was attempted, but failed.
  253. NOTE: this method should call 'self.send_headers()' if
  254. 'self.headers_sent' is false and it is going to attempt direct
  255. transmission of the file.
  256. """
  257. return False # No platform-specific transmission by default
  258. def finish_content(self):
  259. """Ensure headers and content have both been sent"""
  260. if not self.headers_sent:
  261. # Only zero Content-Length if not set by the application (so
  262. # that HEAD requests can be satisfied properly, see #3839)
  263. self.headers.setdefault('Content-Length', "0")
  264. self.send_headers()
  265. else:
  266. pass # XXX check if content-length was too short?
  267. def close(self):
  268. """Close the iterable (if needed) and reset all instance vars
  269. Subclasses may want to also drop the client connection.
  270. """
  271. try:
  272. if hasattr(self.result,'close'):
  273. self.result.close()
  274. finally:
  275. self.result = self.headers = self.status = self.environ = None
  276. self.bytes_sent = 0; self.headers_sent = False
  277. def send_headers(self):
  278. """Transmit headers to the client, via self._write()"""
  279. self.cleanup_headers()
  280. self.headers_sent = True
  281. if not self.origin_server or self.client_is_modern():
  282. self.send_preamble()
  283. self._write(bytes(self.headers))
  284. def result_is_file(self):
  285. """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
  286. wrapper = self.wsgi_file_wrapper
  287. return wrapper is not None and isinstance(self.result,wrapper)
  288. def client_is_modern(self):
  289. """True if client can accept status and headers"""
  290. return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
  291. def log_exception(self,exc_info):
  292. """Log the 'exc_info' tuple in the server log
  293. Subclasses may override to retarget the output or change its format.
  294. """
  295. try:
  296. from traceback import print_exception
  297. stderr = self.get_stderr()
  298. print_exception(
  299. exc_info[0], exc_info[1], exc_info[2],
  300. self.traceback_limit, stderr
  301. )
  302. stderr.flush()
  303. finally:
  304. exc_info = None
  305. def handle_error(self):
  306. """Log current error, and send error output to client if possible"""
  307. self.log_exception(sys.exc_info())
  308. if not self.headers_sent:
  309. self.result = self.error_output(self.environ, self.start_response)
  310. self.finish_response()
  311. # XXX else: attempt advanced recovery techniques for HTML or text?
  312. def error_output(self, environ, start_response):
  313. """WSGI mini-app to create error output
  314. By default, this just uses the 'error_status', 'error_headers',
  315. and 'error_body' attributes to generate an output page. It can
  316. be overridden in a subclass to dynamically generate diagnostics,
  317. choose an appropriate message for the user's preferred language, etc.
  318. Note, however, that it's not recommended from a security perspective to
  319. spit out diagnostics to any old user; ideally, you should have to do
  320. something special to enable diagnostic output, which is why we don't
  321. include any here!
  322. """
  323. start_response(self.error_status,self.error_headers[:],sys.exc_info())
  324. return [self.error_body]
  325. # Pure abstract methods; *must* be overridden in subclasses
  326. def _write(self,data):
  327. """Override in subclass to buffer data for send to client
  328. It's okay if this method actually transmits the data; BaseHandler
  329. just separates write and flush operations for greater efficiency
  330. when the underlying system actually has such a distinction.
  331. """
  332. raise NotImplementedError
  333. def _flush(self):
  334. """Override in subclass to force sending of recent '_write()' calls
  335. It's okay if this method is a no-op (i.e., if '_write()' actually
  336. sends the data.
  337. """
  338. raise NotImplementedError
  339. def get_stdin(self):
  340. """Override in subclass to return suitable 'wsgi.input'"""
  341. raise NotImplementedError
  342. def get_stderr(self):
  343. """Override in subclass to return suitable 'wsgi.errors'"""
  344. raise NotImplementedError
  345. def add_cgi_vars(self):
  346. """Override in subclass to insert CGI variables in 'self.environ'"""
  347. raise NotImplementedError
  348. class SimpleHandler(BaseHandler):
  349. """Handler that's just initialized with streams, environment, etc.
  350. This handler subclass is intended for synchronous HTTP/1.0 origin servers,
  351. and handles sending the entire response output, given the correct inputs.
  352. Usage::
  353. handler = SimpleHandler(
  354. inp,out,err,env, multithread=False, multiprocess=True
  355. )
  356. handler.run(app)"""
  357. def __init__(self,stdin,stdout,stderr,environ,
  358. multithread=True, multiprocess=False
  359. ):
  360. self.stdin = stdin
  361. self.stdout = stdout
  362. self.stderr = stderr
  363. self.base_env = environ
  364. self.wsgi_multithread = multithread
  365. self.wsgi_multiprocess = multiprocess
  366. def get_stdin(self):
  367. return self.stdin
  368. def get_stderr(self):
  369. return self.stderr
  370. def add_cgi_vars(self):
  371. self.environ.update(self.base_env)
  372. def _write(self,data):
  373. result = self.stdout.write(data)
  374. if result is None or result == len(data):
  375. return
  376. from warnings import warn
  377. warn("SimpleHandler.stdout.write() should not do partial writes",
  378. DeprecationWarning)
  379. while True:
  380. data = data[result:]
  381. if not data:
  382. break
  383. result = self.stdout.write(data)
  384. def _flush(self):
  385. self.stdout.flush()
  386. self._flush = self.stdout.flush
  387. class BaseCGIHandler(SimpleHandler):
  388. """CGI-like systems using input/output/error streams and environ mapping
  389. Usage::
  390. handler = BaseCGIHandler(inp,out,err,env)
  391. handler.run(app)
  392. This handler class is useful for gateway protocols like ReadyExec and
  393. FastCGI, that have usable input/output/error streams and an environment
  394. mapping. It's also the base class for CGIHandler, which just uses
  395. sys.stdin, os.environ, and so on.
  396. The constructor also takes keyword arguments 'multithread' and
  397. 'multiprocess' (defaulting to 'True' and 'False' respectively) to control
  398. the configuration sent to the application. It sets 'origin_server' to
  399. False (to enable CGI-like output), and assumes that 'wsgi.run_once' is
  400. False.
  401. """
  402. origin_server = False
  403. class CGIHandler(BaseCGIHandler):
  404. """CGI-based invocation via sys.stdin/stdout/stderr and os.environ
  405. Usage::
  406. CGIHandler().run(app)
  407. The difference between this class and BaseCGIHandler is that it always
  408. uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and
  409. 'wsgi.multiprocess' of 'True'. It does not take any initialization
  410. parameters, but always uses 'sys.stdin', 'os.environ', and friends.
  411. If you need to override any of these parameters, use BaseCGIHandler
  412. instead.
  413. """
  414. wsgi_run_once = True
  415. # Do not allow os.environ to leak between requests in Google App Engine
  416. # and other multi-run CGI use cases. This is not easily testable.
  417. # See http://bugs.python.org/issue7250
  418. os_environ = {}
  419. def __init__(self):
  420. BaseCGIHandler.__init__(
  421. self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr,
  422. read_environ(), multithread=False, multiprocess=True
  423. )
  424. class IISCGIHandler(BaseCGIHandler):
  425. """CGI-based invocation with workaround for IIS path bug
  426. This handler should be used in preference to CGIHandler when deploying on
  427. Microsoft IIS without having set the config allowPathInfo option (IIS>=7)
  428. or metabase allowPathInfoForScriptMappings (IIS<7).
  429. """
  430. wsgi_run_once = True
  431. os_environ = {}
  432. # By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at
  433. # the front, causing problems for WSGI applications that wish to implement
  434. # routing. This handler strips any such duplicated path.
  435. # IIS can be configured to pass the correct PATH_INFO, but this causes
  436. # another bug where PATH_TRANSLATED is wrong. Luckily this variable is
  437. # rarely used and is not guaranteed by WSGI. On IIS<7, though, the
  438. # setting can only be made on a vhost level, affecting all other script
  439. # mappings, many of which break when exposed to the PATH_TRANSLATED bug.
  440. # For this reason IIS<7 is almost never deployed with the fix. (Even IIS7
  441. # rarely uses it because there is still no UI for it.)
  442. # There is no way for CGI code to tell whether the option was set, so a
  443. # separate handler class is provided.
  444. def __init__(self):
  445. environ= read_environ()
  446. path = environ.get('PATH_INFO', '')
  447. script = environ.get('SCRIPT_NAME', '')
  448. if (path+'/').startswith(script+'/'):
  449. environ['PATH_INFO'] = path[len(script):]
  450. BaseCGIHandler.__init__(
  451. self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr,
  452. environ, multithread=False, multiprocess=True
  453. )