wsgi.py 21 KB

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