wsgi.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. An implementation of
  5. U{Python Web Server Gateway Interface v1.0.1<http://www.python.org/dev/peps/pep-3333/>}.
  6. """
  7. from collections.abc import Sequence
  8. from sys import exc_info
  9. from typing import List, Union
  10. from warnings import warn
  11. from zope.interface import implementer
  12. from twisted.internet.threads import blockingCallFromThread
  13. from twisted.logger import Logger
  14. from twisted.python.failure import Failure
  15. from twisted.web.http import INTERNAL_SERVER_ERROR
  16. from twisted.web.resource import IResource
  17. from twisted.web.server import NOT_DONE_YET
  18. # PEP-3333 -- which has superseded PEP-333 -- states that text strings MUST
  19. # be represented using the platform's native string type, limited to
  20. # characters defined in ISO-8859-1. Byte strings are used only for values
  21. # read from wsgi.input, passed to write() or yielded by the application.
  22. #
  23. # Put another way:
  24. #
  25. # - All text strings are of type str, and all binary data are of
  26. # type bytes. Text MUST always be limited to that which can be encoded as
  27. # ISO-8859-1, U+0000 to U+00FF inclusive.
  28. #
  29. # The following pair of functions -- _wsgiString() and _wsgiStringToBytes() --
  30. # are used to make Twisted's WSGI support compliant with the standard.
  31. def _wsgiString(string: Union[str, bytes]) -> str:
  32. """
  33. Convert C{string} to a WSGI "bytes-as-unicode" string.
  34. If it's a byte string, decode as ISO-8859-1. If it's a Unicode string,
  35. round-trip it to bytes and back using ISO-8859-1 as the encoding.
  36. @type string: C{str} or C{bytes}
  37. @rtype: C{str}
  38. @raise UnicodeEncodeError: If C{string} contains non-ISO-8859-1 chars.
  39. """
  40. if isinstance(string, str):
  41. return string.encode("iso-8859-1").decode("iso-8859-1")
  42. else:
  43. return string.decode("iso-8859-1")
  44. def _wsgiStringToBytes(string: str) -> bytes:
  45. """
  46. Convert C{string} from a WSGI "bytes-as-unicode" string to an
  47. ISO-8859-1 byte string.
  48. @type string: C{str}
  49. @rtype: C{bytes}
  50. @raise UnicodeEncodeError: If C{string} contains non-ISO-8859-1 chars.
  51. """
  52. return string.encode("iso-8859-1")
  53. class _ErrorStream:
  54. """
  55. File-like object instances of which are used as the value for the
  56. C{'wsgi.errors'} key in the C{environ} dictionary passed to the application
  57. object.
  58. This simply passes writes on to L{logging<twisted.logger>} system as
  59. error events from the C{'wsgi'} system. In the future, it may be desirable
  60. to expose more information in the events it logs, such as the application
  61. object which generated the message.
  62. """
  63. _log = Logger()
  64. def write(self, data: str) -> None:
  65. """
  66. Generate an event for the logging system with the given bytes as the
  67. message.
  68. This is called in a WSGI application thread, not the I/O thread.
  69. @type data: str
  70. @raise TypeError: if C{data} is not a native string.
  71. """
  72. if not isinstance(data, str):
  73. raise TypeError(
  74. "write() argument must be str, not %r (%s)"
  75. % (data, type(data).__name__)
  76. )
  77. # Note that in old style, message was a tuple. logger._legacy
  78. # will overwrite this value if it is not properly formatted here.
  79. self._log.error(data, system="wsgi", isError=True, message=(data,))
  80. def writelines(self, iovec: List[str]) -> None:
  81. """
  82. Join the given lines and pass them to C{write} to be handled in the
  83. usual way.
  84. This is called in a WSGI application thread, not the I/O thread.
  85. @param iovec: A C{list} of C{'\\n'}-terminated C{str} which will be
  86. logged.
  87. @raise TypeError: if C{iovec} contains any non-native strings.
  88. """
  89. self.write("".join(iovec))
  90. def flush(self):
  91. """
  92. Nothing is buffered, so flushing does nothing. This method is required
  93. to exist by PEP 333, though.
  94. This is called in a WSGI application thread, not the I/O thread.
  95. """
  96. class _InputStream:
  97. """
  98. File-like object instances of which are used as the value for the
  99. C{'wsgi.input'} key in the C{environ} dictionary passed to the application
  100. object.
  101. This only exists to make the handling of C{readline(-1)} consistent across
  102. different possible underlying file-like object implementations. The other
  103. supported methods pass through directly to the wrapped object.
  104. """
  105. def __init__(self, input):
  106. """
  107. Initialize the instance.
  108. This is called in the I/O thread, not a WSGI application thread.
  109. """
  110. self._wrapped = input
  111. def read(self, size=None):
  112. """
  113. Pass through to the underlying C{read}.
  114. This is called in a WSGI application thread, not the I/O thread.
  115. """
  116. # Avoid passing None because cStringIO and file don't like it.
  117. if size is None:
  118. return self._wrapped.read()
  119. return self._wrapped.read(size)
  120. def readline(self, size=None):
  121. """
  122. Pass through to the underlying C{readline}, with a size of C{-1} replaced
  123. with a size of L{None}.
  124. This is called in a WSGI application thread, not the I/O thread.
  125. """
  126. # Check for -1 because StringIO doesn't handle it correctly. Check for
  127. # None because files and tempfiles don't accept that.
  128. if size == -1 or size is None:
  129. return self._wrapped.readline()
  130. return self._wrapped.readline(size)
  131. def readlines(self, size=None):
  132. """
  133. Pass through to the underlying C{readlines}.
  134. This is called in a WSGI application thread, not the I/O thread.
  135. """
  136. # Avoid passing None because cStringIO and file don't like it.
  137. if size is None:
  138. return self._wrapped.readlines()
  139. return self._wrapped.readlines(size)
  140. def __iter__(self):
  141. """
  142. Pass through to the underlying C{__iter__}.
  143. This is called in a WSGI application thread, not the I/O thread.
  144. """
  145. return iter(self._wrapped)
  146. class _WSGIResponse:
  147. """
  148. Helper for L{WSGIResource} which drives the WSGI application using a
  149. threadpool and hooks it up to the L{http.Request}.
  150. @ivar started: A L{bool} indicating whether or not the response status and
  151. headers have been written to the request yet. This may only be read or
  152. written in the WSGI application thread.
  153. @ivar reactor: An L{IReactorThreads} provider which is used to call methods
  154. on the request in the I/O thread.
  155. @ivar threadpool: A L{ThreadPool} which is used to call the WSGI
  156. application object in a non-I/O thread.
  157. @ivar application: The WSGI application object.
  158. @ivar request: The L{http.Request} upon which the WSGI environment is
  159. based and to which the application's output will be sent.
  160. @ivar environ: The WSGI environment L{dict}.
  161. @ivar status: The HTTP response status L{str} supplied to the WSGI
  162. I{start_response} callable by the application.
  163. @ivar headers: A list of HTTP response headers supplied to the WSGI
  164. I{start_response} callable by the application.
  165. @ivar _requestFinished: A flag which indicates whether it is possible to
  166. generate more response data or not. This is L{False} until
  167. L{http.Request.notifyFinish} tells us the request is done,
  168. then L{True}.
  169. """
  170. _requestFinished = False
  171. _log = Logger()
  172. def __init__(self, reactor, threadpool, application, request):
  173. self.started = False
  174. self.reactor = reactor
  175. self.threadpool = threadpool
  176. self.application = application
  177. self.request = request
  178. self.request.notifyFinish().addBoth(self._finished)
  179. if request.prepath:
  180. scriptName = b"/" + b"/".join(request.prepath)
  181. else:
  182. scriptName = b""
  183. if request.postpath:
  184. pathInfo = b"/" + b"/".join(request.postpath)
  185. else:
  186. pathInfo = b""
  187. parts = request.uri.split(b"?", 1)
  188. if len(parts) == 1:
  189. queryString = b""
  190. else:
  191. queryString = parts[1]
  192. # All keys and values need to be native strings, i.e. of type str in
  193. # *both* Python 2 and Python 3, so says PEP-3333.
  194. remotePeer = request.getClientAddress()
  195. self.environ = {
  196. "REQUEST_METHOD": _wsgiString(request.method),
  197. "REMOTE_ADDR": _wsgiString(remotePeer.host),
  198. "REMOTE_PORT": _wsgiString(str(remotePeer.port)),
  199. "SCRIPT_NAME": _wsgiString(scriptName),
  200. "PATH_INFO": _wsgiString(pathInfo),
  201. "QUERY_STRING": _wsgiString(queryString),
  202. "CONTENT_TYPE": _wsgiString(request.getHeader(b"content-type") or ""),
  203. "CONTENT_LENGTH": _wsgiString(request.getHeader(b"content-length") or ""),
  204. "SERVER_NAME": _wsgiString(request.getRequestHostname()),
  205. "SERVER_PORT": _wsgiString(str(request.getHost().port)),
  206. "SERVER_PROTOCOL": _wsgiString(request.clientproto),
  207. }
  208. # The application object is entirely in control of response headers;
  209. # disable the default Content-Type value normally provided by
  210. # twisted.web.server.Request.
  211. self.request.defaultContentType = None
  212. for name, values in request.requestHeaders.getAllRawHeaders():
  213. name = "HTTP_" + _wsgiString(name).upper().replace("-", "_")
  214. # It might be preferable for http.HTTPChannel to clear out
  215. # newlines.
  216. self.environ[name] = ",".join(_wsgiString(v) for v in values).replace(
  217. "\n", " "
  218. )
  219. self.environ.update(
  220. {
  221. "wsgi.version": (1, 0),
  222. "wsgi.url_scheme": request.isSecure() and "https" or "http",
  223. "wsgi.run_once": False,
  224. "wsgi.multithread": True,
  225. "wsgi.multiprocess": False,
  226. "wsgi.errors": _ErrorStream(),
  227. # Attend: request.content was owned by the I/O thread up until
  228. # this point. By wrapping it and putting the result into the
  229. # environment dictionary, it is effectively being given to
  230. # another thread. This means that whatever it is, it has to be
  231. # safe to access it from two different threads. The access
  232. # *should* all be serialized (first the I/O thread writes to
  233. # it, then the WSGI thread reads from it, then the I/O thread
  234. # closes it). However, since the request is made available to
  235. # arbitrary application code during resource traversal, it's
  236. # possible that some other code might decide to use it in the
  237. # I/O thread concurrently with its use in the WSGI thread.
  238. # More likely than not, this will break. This seems like an
  239. # unlikely possibility to me, but if it is to be allowed,
  240. # something here needs to change. -exarkun
  241. "wsgi.input": _InputStream(request.content),
  242. }
  243. )
  244. def _finished(self, ignored):
  245. """
  246. Record the end of the response generation for the request being
  247. serviced.
  248. """
  249. self._requestFinished = True
  250. def startResponse(self, status, headers, excInfo=None):
  251. """
  252. The WSGI I{start_response} callable. The given values are saved until
  253. they are needed to generate the response.
  254. This will be called in a non-I/O thread.
  255. """
  256. if self.started and excInfo is not None:
  257. raise excInfo[1].with_traceback(excInfo[2])
  258. # PEP-3333 mandates that status should be a native string. In practice
  259. # this is mandated by Twisted's HTTP implementation too.
  260. if not isinstance(status, str):
  261. raise TypeError(
  262. "status must be str, not {!r} ({})".format(
  263. status, type(status).__name__
  264. )
  265. )
  266. # PEP-3333 mandates that headers should be a plain list, but in
  267. # practice we work with any sequence type and only warn when it's not
  268. # a plain list.
  269. if isinstance(headers, list):
  270. pass # This is okay.
  271. elif isinstance(headers, Sequence):
  272. warn(
  273. "headers should be a list, not %r (%s)"
  274. % (headers, type(headers).__name__),
  275. category=RuntimeWarning,
  276. )
  277. else:
  278. raise TypeError(
  279. "headers must be a list, not %r (%s)"
  280. % (headers, type(headers).__name__)
  281. )
  282. # PEP-3333 mandates that each header should be a (str, str) tuple, but
  283. # in practice we work with any sequence type and only warn when it's
  284. # not a plain list.
  285. for header in headers:
  286. if isinstance(header, tuple):
  287. pass # This is okay.
  288. elif isinstance(header, Sequence):
  289. warn(
  290. "header should be a (str, str) tuple, not %r (%s)"
  291. % (header, type(header).__name__),
  292. category=RuntimeWarning,
  293. )
  294. else:
  295. raise TypeError(
  296. "header must be a (str, str) tuple, not %r (%s)"
  297. % (header, type(header).__name__)
  298. )
  299. # However, the sequence MUST contain only 2 elements.
  300. if len(header) != 2:
  301. raise TypeError(f"header must be a (str, str) tuple, not {header!r}")
  302. # Both elements MUST be native strings. Non-native strings will be
  303. # rejected by the underlying HTTP machinery in any case, but we
  304. # reject them here in order to provide a more informative error.
  305. for elem in header:
  306. if not isinstance(elem, str):
  307. raise TypeError(f"header must be (str, str) tuple, not {header!r}")
  308. self.status = status
  309. self.headers = headers
  310. return self.write
  311. def write(self, data):
  312. """
  313. The WSGI I{write} callable returned by the I{start_response} callable.
  314. The given bytes will be written to the response body, possibly flushing
  315. the status and headers first.
  316. This will be called in a non-I/O thread.
  317. """
  318. # PEP-3333 states:
  319. #
  320. # The server or gateway must transmit the yielded bytestrings to the
  321. # client in an unbuffered fashion, completing the transmission of
  322. # each bytestring before requesting another one.
  323. #
  324. # This write() method is used for the imperative and (indirectly) for
  325. # the more familiar iterable-of-bytestrings WSGI mechanism. It uses
  326. # C{blockingCallFromThread} to schedule writes. This allows exceptions
  327. # to propagate up from the underlying HTTP implementation. However,
  328. # that underlying implementation does not, as yet, provide any way to
  329. # know if the written data has been transmitted, so this method
  330. # violates the above part of PEP-3333.
  331. #
  332. # PEP-3333 also says that a server may:
  333. #
  334. # Use a different thread to ensure that the block continues to be
  335. # transmitted while the application produces the next block.
  336. #
  337. # Which suggests that this is actually compliant with PEP-3333,
  338. # because writes are done in the reactor thread.
  339. #
  340. # However, providing some back-pressure may nevertheless be a Good
  341. # Thing at some point in the future.
  342. def wsgiWrite(started):
  343. if not started:
  344. self._sendResponseHeaders()
  345. self.request.write(data)
  346. try:
  347. return blockingCallFromThread(self.reactor, wsgiWrite, self.started)
  348. finally:
  349. self.started = True
  350. def _sendResponseHeaders(self):
  351. """
  352. Set the response code and response headers on the request object, but
  353. do not flush them. The caller is responsible for doing a write in
  354. order for anything to actually be written out in response to the
  355. request.
  356. This must be called in the I/O thread.
  357. """
  358. code, message = self.status.split(None, 1)
  359. code = int(code)
  360. self.request.setResponseCode(code, _wsgiStringToBytes(message))
  361. for name, value in self.headers:
  362. # Don't allow the application to control these required headers.
  363. if name.lower() not in ("server", "date"):
  364. self.request.responseHeaders.addRawHeader(
  365. _wsgiStringToBytes(name), _wsgiStringToBytes(value)
  366. )
  367. def start(self):
  368. """
  369. Start the WSGI application in the threadpool.
  370. This must be called in the I/O thread.
  371. """
  372. self.threadpool.callInThread(self.run)
  373. def run(self):
  374. """
  375. Call the WSGI application object, iterate it, and handle its output.
  376. This must be called in a non-I/O thread (ie, a WSGI application
  377. thread).
  378. """
  379. try:
  380. appIterator = self.application(self.environ, self.startResponse)
  381. for elem in appIterator:
  382. if elem:
  383. self.write(elem)
  384. if self._requestFinished:
  385. break
  386. close = getattr(appIterator, "close", None)
  387. if close is not None:
  388. close()
  389. except BaseException:
  390. def wsgiError(started, type, value, traceback):
  391. self._log.failure(
  392. "WSGI application error", failure=Failure(value, type, traceback)
  393. )
  394. if started:
  395. self.request.loseConnection()
  396. else:
  397. self.request.setResponseCode(INTERNAL_SERVER_ERROR)
  398. self.request.finish()
  399. self.reactor.callFromThread(wsgiError, self.started, *exc_info())
  400. else:
  401. def wsgiFinish(started):
  402. if not self._requestFinished:
  403. if not started:
  404. self._sendResponseHeaders()
  405. self.request.finish()
  406. self.reactor.callFromThread(wsgiFinish, self.started)
  407. self.started = True
  408. @implementer(IResource)
  409. class WSGIResource:
  410. """
  411. An L{IResource} implementation which delegates responsibility for all
  412. resources hierarchically inferior to it to a WSGI application.
  413. The C{environ} argument passed to the application, includes the
  414. C{REMOTE_PORT} key to complement the C{REMOTE_ADDR} key.
  415. @ivar _reactor: An L{IReactorThreads} provider which will be passed on to
  416. L{_WSGIResponse} to schedule calls in the I/O thread.
  417. @ivar _threadpool: A L{ThreadPool} which will be passed on to
  418. L{_WSGIResponse} to run the WSGI application object.
  419. @ivar _application: The WSGI application object.
  420. """
  421. # Further resource segments are left up to the WSGI application object to
  422. # handle.
  423. isLeaf = True
  424. def __init__(self, reactor, threadpool, application):
  425. self._reactor = reactor
  426. self._threadpool = threadpool
  427. self._application = application
  428. def render(self, request):
  429. """
  430. Turn the request into the appropriate C{environ} C{dict} suitable to be
  431. passed to the WSGI application object and then pass it on.
  432. The WSGI application object is given almost complete control of the
  433. rendering process. C{NOT_DONE_YET} will always be returned in order
  434. and response completion will be dictated by the application object, as
  435. will the status, headers, and the response body.
  436. """
  437. response = _WSGIResponse(
  438. self._reactor, self._threadpool, self._application, request
  439. )
  440. response.start()
  441. return NOT_DONE_YET
  442. def getChildWithDefault(self, name, request):
  443. """
  444. Reject attempts to retrieve a child resource. All path segments beyond
  445. the one which refers to this resource are handled by the WSGI
  446. application object.
  447. """
  448. raise RuntimeError("Cannot get IResource children from WSGIResource")
  449. def putChild(self, path, child):
  450. """
  451. Reject attempts to add a child resource to this resource. The WSGI
  452. application object handles all path segments beneath this resource, so
  453. L{IResource} children can never be found.
  454. """
  455. raise RuntimeError("Cannot put IResource children under WSGIResource")
  456. __all__ = ["WSGIResource"]