wsgi.py 21 KB

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