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.

websocket.py 12KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) Crossbar.io Technologies 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 __future__ import absolute_import
  27. from collections import deque
  28. import txaio
  29. txaio.use_asyncio()
  30. from autobahn.util import public
  31. from autobahn.asyncio.util import transport_channel_id, peer2str
  32. from autobahn.wamp import websocket
  33. from autobahn.websocket import protocol
  34. from autobahn.websocket.types import TransportDetails
  35. try:
  36. import asyncio
  37. from asyncio import iscoroutine
  38. from asyncio import Future
  39. except ImportError:
  40. # Trollius >= 0.3 was renamed
  41. # noinspection PyUnresolvedReferences
  42. import trollius as asyncio
  43. from trollius import iscoroutine
  44. from trollius import Future
  45. if hasattr(asyncio, 'ensure_future'):
  46. ensure_future = asyncio.ensure_future
  47. else: # Deprecated since Python 3.4.4
  48. ensure_future = getattr(asyncio, 'async')
  49. __all__ = (
  50. 'WebSocketServerProtocol',
  51. 'WebSocketClientProtocol',
  52. 'WebSocketServerFactory',
  53. 'WebSocketClientFactory',
  54. 'WampWebSocketServerProtocol',
  55. 'WampWebSocketClientProtocol',
  56. 'WampWebSocketServerFactory',
  57. 'WampWebSocketClientFactory',
  58. )
  59. def yields(value):
  60. """
  61. Returns ``True`` iff the value yields.
  62. .. seealso:: http://stackoverflow.com/questions/20730248/maybedeferred-analog-with-asyncio
  63. """
  64. return isinstance(value, Future) or iscoroutine(value)
  65. class WebSocketAdapterProtocol(asyncio.Protocol):
  66. """
  67. Adapter class for asyncio-based WebSocket client and server protocols.
  68. """
  69. def connection_made(self, transport):
  70. self.transport = transport
  71. self.receive_queue = deque()
  72. self._consume()
  73. try:
  74. self.peer = peer2str(transport.get_extra_info('peername'))
  75. except:
  76. self.peer = u"?"
  77. self._connectionMade()
  78. def connection_lost(self, exc):
  79. self._connectionLost(exc)
  80. # according to asyncio docs, connection_lost(None) is called
  81. # if something else called transport.close()
  82. if exc is not None:
  83. self.transport.close()
  84. self.transport = None
  85. def _consume(self):
  86. self.waiter = Future(loop=self.factory.loop or txaio.config.loop)
  87. def process(_):
  88. while len(self.receive_queue):
  89. data = self.receive_queue.popleft()
  90. if self.transport:
  91. self._dataReceived(data)
  92. self._consume()
  93. self.waiter.add_done_callback(process)
  94. def data_received(self, data):
  95. self.receive_queue.append(data)
  96. if not self.waiter.done():
  97. self.waiter.set_result(None)
  98. def _closeConnection(self, abort=False):
  99. if abort and hasattr(self.transport, 'abort'):
  100. self.transport.abort()
  101. else:
  102. self.transport.close()
  103. def _onOpen(self):
  104. res = self.onOpen()
  105. if yields(res):
  106. ensure_future(res)
  107. def _onMessageBegin(self, isBinary):
  108. res = self.onMessageBegin(isBinary)
  109. if yields(res):
  110. ensure_future(res)
  111. def _onMessageFrameBegin(self, length):
  112. res = self.onMessageFrameBegin(length)
  113. if yields(res):
  114. ensure_future(res)
  115. def _onMessageFrameData(self, payload):
  116. res = self.onMessageFrameData(payload)
  117. if yields(res):
  118. ensure_future(res)
  119. def _onMessageFrameEnd(self):
  120. res = self.onMessageFrameEnd()
  121. if yields(res):
  122. ensure_future(res)
  123. def _onMessageFrame(self, payload):
  124. res = self.onMessageFrame(payload)
  125. if yields(res):
  126. ensure_future(res)
  127. def _onMessageEnd(self):
  128. res = self.onMessageEnd()
  129. if yields(res):
  130. ensure_future(res)
  131. def _onMessage(self, payload, isBinary):
  132. res = self.onMessage(payload, isBinary)
  133. if yields(res):
  134. ensure_future(res)
  135. def _onPing(self, payload):
  136. res = self.onPing(payload)
  137. if yields(res):
  138. ensure_future(res)
  139. def _onPong(self, payload):
  140. res = self.onPong(payload)
  141. if yields(res):
  142. ensure_future(res)
  143. def _onClose(self, wasClean, code, reason):
  144. res = self.onClose(wasClean, code, reason)
  145. if yields(res):
  146. ensure_future(res)
  147. def registerProducer(self, producer, streaming):
  148. raise Exception("not implemented")
  149. def unregisterProducer(self):
  150. # note that generic websocket/protocol.py code calls
  151. # .unregisterProducer whenever we dropConnection -- that's
  152. # correct behavior on Twisted so either we'd have to
  153. # try/except there, or special-case Twisted, ..or just make
  154. # this "not an error"
  155. pass
  156. @public
  157. class WebSocketServerProtocol(WebSocketAdapterProtocol, protocol.WebSocketServerProtocol):
  158. """
  159. Base class for asyncio-based WebSocket server protocols.
  160. Implements:
  161. * :class:`autobahn.websocket.interfaces.IWebSocketChannel`
  162. """
  163. log = txaio.make_logger()
  164. def get_channel_id(self, channel_id_type=u'tls-unique'):
  165. """
  166. Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id`
  167. """
  168. return transport_channel_id(self.transport, True, channel_id_type)
  169. @public
  170. class WebSocketClientProtocol(WebSocketAdapterProtocol, protocol.WebSocketClientProtocol):
  171. """
  172. Base class for asyncio-based WebSocket client protocols.
  173. Implements:
  174. * :class:`autobahn.websocket.interfaces.IWebSocketChannel`
  175. """
  176. log = txaio.make_logger()
  177. def _onConnect(self, response):
  178. res = self.onConnect(response)
  179. if yields(res):
  180. ensure_future(res)
  181. def startTLS(self):
  182. raise Exception("WSS over explicit proxies not implemented")
  183. def get_channel_id(self, channel_id_type=u'tls-unique'):
  184. """
  185. Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id`
  186. """
  187. return transport_channel_id(self.transport, False, channel_id_type)
  188. def _create_transport_details(self):
  189. """
  190. Internal helper.
  191. Base class calls this to create a TransportDetails
  192. """
  193. is_secure = self.transport.get_extra_info('peercert', None) is not None
  194. if is_secure:
  195. secure_channel_id = {
  196. u'tls-unique': transport_channel_id(self.transport, False, 'tls-unique'),
  197. }
  198. else:
  199. secure_channel_id = {}
  200. return TransportDetails(peer=self.peer, is_secure=is_secure, secure_channel_id=secure_channel_id)
  201. class WebSocketAdapterFactory(object):
  202. """
  203. Adapter class for asyncio-based WebSocket client and server factories.
  204. """
  205. log = txaio.make_logger()
  206. def __call__(self):
  207. proto = self.protocol()
  208. proto.factory = self
  209. return proto
  210. @public
  211. class WebSocketServerFactory(WebSocketAdapterFactory, protocol.WebSocketServerFactory):
  212. """
  213. Base class for asyncio-based WebSocket server factories.
  214. Implements:
  215. * :class:`autobahn.websocket.interfaces.IWebSocketServerChannelFactory`
  216. """
  217. protocol = WebSocketServerProtocol
  218. def __init__(self, *args, **kwargs):
  219. """
  220. .. note::
  221. In addition to all arguments to the constructor of
  222. :meth:`autobahn.websocket.interfaces.IWebSocketServerChannelFactory`,
  223. you can supply a ``loop`` keyword argument to specify the
  224. asyncio event loop to be used.
  225. """
  226. loop = kwargs.pop('loop', None)
  227. self.loop = loop or asyncio.get_event_loop()
  228. protocol.WebSocketServerFactory.__init__(self, *args, **kwargs)
  229. @public
  230. class WebSocketClientFactory(WebSocketAdapterFactory, protocol.WebSocketClientFactory):
  231. """
  232. Base class for asyncio-based WebSocket client factories.
  233. Implements:
  234. * :class:`autobahn.websocket.interfaces.IWebSocketClientChannelFactory`
  235. """
  236. def __init__(self, *args, **kwargs):
  237. """
  238. .. note::
  239. In addition to all arguments to the constructor of
  240. :meth:`autobahn.websocket.interfaces.IWebSocketClientChannelFactory`,
  241. you can supply a ``loop`` keyword argument to specify the
  242. asyncio event loop to be used.
  243. """
  244. loop = kwargs.pop('loop', None)
  245. self.loop = loop or asyncio.get_event_loop()
  246. protocol.WebSocketClientFactory.__init__(self, *args, **kwargs)
  247. @public
  248. class WampWebSocketServerProtocol(websocket.WampWebSocketServerProtocol, WebSocketServerProtocol):
  249. """
  250. asyncio-based WAMP-over-WebSocket server protocol.
  251. Implements:
  252. * :class:`autobahn.wamp.interfaces.ITransport`
  253. """
  254. @public
  255. class WampWebSocketServerFactory(websocket.WampWebSocketServerFactory, WebSocketServerFactory):
  256. """
  257. asyncio-based WAMP-over-WebSocket server factory.
  258. """
  259. protocol = WampWebSocketServerProtocol
  260. def __init__(self, factory, *args, **kwargs):
  261. """
  262. :param factory: A callable that produces instances that implement
  263. :class:`autobahn.wamp.interfaces.ITransportHandler`
  264. :type factory: callable
  265. :param serializers: A list of WAMP serializers to use (or ``None``
  266. for all available serializers).
  267. :type serializers: list of objects implementing
  268. :class:`autobahn.wamp.interfaces.ISerializer`
  269. """
  270. serializers = kwargs.pop('serializers', None)
  271. websocket.WampWebSocketServerFactory.__init__(self, factory, serializers)
  272. kwargs['protocols'] = self._protocols
  273. # noinspection PyCallByClass
  274. WebSocketServerFactory.__init__(self, *args, **kwargs)
  275. @public
  276. class WampWebSocketClientProtocol(websocket.WampWebSocketClientProtocol, WebSocketClientProtocol):
  277. """
  278. asyncio-based WAMP-over-WebSocket client protocols.
  279. Implements:
  280. * :class:`autobahn.wamp.interfaces.ITransport`
  281. """
  282. @public
  283. class WampWebSocketClientFactory(websocket.WampWebSocketClientFactory, WebSocketClientFactory):
  284. """
  285. asyncio-based WAMP-over-WebSocket client factory.
  286. """
  287. protocol = WampWebSocketClientProtocol
  288. def __init__(self, factory, *args, **kwargs):
  289. """
  290. :param factory: A callable that produces instances that implement
  291. :class:`autobahn.wamp.interfaces.ITransportHandler`
  292. :type factory: callable
  293. :param serializer: The WAMP serializer to use (or ``None`` for
  294. "best" serializer, chosen as the first serializer available from
  295. this list: CBOR, MessagePack, UBJSON, JSON).
  296. :type serializer: object implementing :class:`autobahn.wamp.interfaces.ISerializer`
  297. """
  298. serializers = kwargs.pop('serializers', None)
  299. websocket.WampWebSocketClientFactory.__init__(self, factory, serializers)
  300. kwargs['protocols'] = self._protocols
  301. WebSocketClientFactory.__init__(self, *args, **kwargs)