handlers.py 21 KB

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