Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

resource.py 7.0KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. from zope.interface import implementer
  27. from twisted.protocols.policies import ProtocolWrapper
  28. try:
  29. # starting from Twisted 22.10.0 we have `notFound`
  30. from twisted.web.pages import notFound
  31. except ImportError:
  32. try:
  33. # In Twisted < 22.10.0 && > 12.2 this was called `NoResource`
  34. from twisted.web.resource import NoResource as notFound
  35. except ImportError:
  36. # And in Twisted < 12.2 this was in a different place
  37. from twisted.web.error import NoResource as notFound
  38. from twisted.web.resource import IResource, Resource
  39. # The following triggers an import of reactor at module level!
  40. #
  41. from twisted.web.server import NOT_DONE_YET
  42. __all__ = (
  43. 'WebSocketResource',
  44. 'WSGIRootResource',
  45. )
  46. class WSGIRootResource(Resource):
  47. """
  48. Root resource when you want a WSGI resource be the default serving
  49. resource for a Twisted Web site, but have subpaths served by
  50. different resources.
  51. This is a hack needed since
  52. `twisted.web.wsgi.WSGIResource <http://twistedmatrix.com/documents/current/api/twisted.web.wsgi.WSGIResource.html>`_.
  53. does not provide a ``putChild()`` method.
  54. .. seealso::
  55. * `Autobahn Twisted Web WSGI example <https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_wsgi>`_
  56. * `Original hack <http://blog.vrplumber.com/index.php?/archives/2426-Making-your-Twisted-resources-a-url-sub-tree-of-your-WSGI-resource....html>`_
  57. """
  58. def __init__(self, wsgiResource, children):
  59. """
  60. :param wsgiResource: The WSGI to serve as root resource.
  61. :type wsgiResource: Instance of `twisted.web.wsgi.WSGIResource <http://twistedmatrix.com/documents/current/api/twisted.web.wsgi.WSGIResource.html>`_.
  62. :param children: A dictionary with string keys constituting URL subpaths, and Twisted Web resources as values.
  63. :type children: dict
  64. """
  65. Resource.__init__(self)
  66. self._wsgiResource = wsgiResource
  67. self.children = children
  68. def getChild(self, path, request):
  69. request.prepath.pop()
  70. request.postpath.insert(0, path)
  71. return self._wsgiResource
  72. @implementer(IResource)
  73. class WebSocketResource(object):
  74. """
  75. A Twisted Web resource for WebSocket.
  76. """
  77. isLeaf = True
  78. def __init__(self, factory):
  79. """
  80. :param factory: An instance of :class:`autobahn.twisted.websocket.WebSocketServerFactory`.
  81. :type factory: obj
  82. """
  83. self._factory = factory
  84. # noinspection PyUnusedLocal
  85. def getChildWithDefault(self, name, request):
  86. """
  87. This resource cannot have children, hence this will always fail.
  88. """
  89. return notFound(message="No such child resource.")
  90. def putChild(self, path, child):
  91. """
  92. This resource cannot have children, hence this is always ignored.
  93. """
  94. def render(self, request):
  95. """
  96. Render the resource. This will takeover the transport underlying
  97. the request, create a :class:`autobahn.twisted.websocket.WebSocketServerProtocol`
  98. and let that do any subsequent communication.
  99. """
  100. # for reasons unknown, the transport is already None when the
  101. # request is over HTTP2. request.channel.getPeer() is valid at
  102. # this point however
  103. if request.channel.transport is None:
  104. # render an "error, yo're doing HTTPS over WSS" webpage
  105. from autobahn.websocket import protocol
  106. request.setResponseCode(426, b"Upgrade required")
  107. # RFC says MUST set upgrade along with 426 code:
  108. # https://tools.ietf.org/html/rfc7231#section-6.5.15
  109. request.setHeader(b"Upgrade", b"WebSocket")
  110. html = protocol._SERVER_STATUS_TEMPLATE % ("", protocol.__version__)
  111. return html.encode('utf8')
  112. # Create Autobahn WebSocket protocol.
  113. #
  114. protocol = self._factory.buildProtocol(request.transport.getPeer())
  115. if not protocol:
  116. # If protocol creation fails, we signal "internal server error"
  117. request.setResponseCode(500)
  118. return b""
  119. # Take over the transport from Twisted Web
  120. #
  121. transport, request.channel.transport = request.channel.transport, None
  122. # Connect the transport to our protocol. Once #3204 is fixed, there
  123. # may be a cleaner way of doing this.
  124. # http://twistedmatrix.com/trac/ticket/3204
  125. #
  126. if isinstance(transport, ProtocolWrapper):
  127. # i.e. TLS is a wrapping protocol
  128. transport.wrappedProtocol = protocol
  129. elif isinstance(transport.protocol, ProtocolWrapper):
  130. # this happens in new-TLS
  131. transport.protocol.wrappedProtocol = protocol
  132. else:
  133. transport.protocol = protocol
  134. protocol.makeConnection(transport)
  135. # On Twisted 16+, the transport is paused whilst the existing
  136. # request is served; there won't be any requests after us so
  137. # we can just resume this ourselves.
  138. # 17.1 version
  139. if hasattr(transport, "_networkProducer"):
  140. transport._networkProducer.resumeProducing()
  141. # 16.x version
  142. elif hasattr(transport, "resumeProducing"):
  143. transport.resumeProducing()
  144. # We recreate the request and forward the raw data. This is somewhat
  145. # silly (since Twisted Web already did the HTTP request parsing
  146. # which we will do a 2nd time), but it's totally non-invasive to our
  147. # code. Maybe improve this.
  148. #
  149. data = request.method + b' ' + request.uri + b' HTTP/1.1\x0d\x0a'
  150. for h in request.requestHeaders.getAllRawHeaders():
  151. data += h[0] + b': ' + b",".join(h[1]) + b'\x0d\x0a'
  152. data += b"\x0d\x0a"
  153. data += request.content.read()
  154. protocol.dataReceived(data)
  155. return NOT_DONE_YET