websocket.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. """Implementation of the WebSocket protocol.
  2. `WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
  3. communication between the browser and server.
  4. WebSockets are supported in the current versions of all major browsers,
  5. although older versions that do not support WebSockets are still in use
  6. (refer to http://caniuse.com/websockets for details).
  7. This module implements the final version of the WebSocket protocol as
  8. defined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_. Certain
  9. browser versions (notably Safari 5.x) implemented an earlier draft of
  10. the protocol (known as "draft 76") and are not compatible with this module.
  11. .. versionchanged:: 4.0
  12. Removed support for the draft 76 protocol version.
  13. """
  14. from __future__ import absolute_import, division, print_function, with_statement
  15. # Author: Jacob Kristhammar, 2010
  16. import base64
  17. import collections
  18. import hashlib
  19. import os
  20. import struct
  21. import tornado.escape
  22. import tornado.web
  23. import zlib
  24. from tornado.concurrent import TracebackFuture
  25. from tornado.escape import utf8, native_str, to_unicode
  26. from tornado import httpclient, httputil
  27. from tornado.ioloop import IOLoop
  28. from tornado.iostream import StreamClosedError
  29. from tornado.log import gen_log, app_log
  30. from tornado import simple_httpclient
  31. from tornado.tcpclient import TCPClient
  32. from tornado.util import _websocket_mask
  33. try:
  34. from urllib.parse import urlparse # py2
  35. except ImportError:
  36. from urlparse import urlparse # py3
  37. try:
  38. xrange # py2
  39. except NameError:
  40. xrange = range # py3
  41. class WebSocketError(Exception):
  42. pass
  43. class WebSocketClosedError(WebSocketError):
  44. """Raised by operations on a closed connection.
  45. .. versionadded:: 3.2
  46. """
  47. pass
  48. class WebSocketHandler(tornado.web.RequestHandler):
  49. """Subclass this class to create a basic WebSocket handler.
  50. Override `on_message` to handle incoming messages, and use
  51. `write_message` to send messages to the client. You can also
  52. override `open` and `on_close` to handle opened and closed
  53. connections.
  54. See http://dev.w3.org/html5/websockets/ for details on the
  55. JavaScript interface. The protocol is specified at
  56. http://tools.ietf.org/html/rfc6455.
  57. Here is an example WebSocket handler that echos back all received messages
  58. back to the client:
  59. .. testcode::
  60. class EchoWebSocket(tornado.websocket.WebSocketHandler):
  61. def open(self):
  62. print("WebSocket opened")
  63. def on_message(self, message):
  64. self.write_message(u"You said: " + message)
  65. def on_close(self):
  66. print("WebSocket closed")
  67. .. testoutput::
  68. :hide:
  69. WebSockets are not standard HTTP connections. The "handshake" is
  70. HTTP, but after the handshake, the protocol is
  71. message-based. Consequently, most of the Tornado HTTP facilities
  72. are not available in handlers of this type. The only communication
  73. methods available to you are `write_message()`, `ping()`, and
  74. `close()`. Likewise, your request handler class should implement
  75. `open()` method rather than ``get()`` or ``post()``.
  76. If you map the handler above to ``/websocket`` in your application, you can
  77. invoke it in JavaScript with::
  78. var ws = new WebSocket("ws://localhost:8888/websocket");
  79. ws.onopen = function() {
  80. ws.send("Hello, world");
  81. };
  82. ws.onmessage = function (evt) {
  83. alert(evt.data);
  84. };
  85. This script pops up an alert box that says "You said: Hello, world".
  86. Web browsers allow any site to open a websocket connection to any other,
  87. instead of using the same-origin policy that governs other network
  88. access from javascript. This can be surprising and is a potential
  89. security hole, so since Tornado 4.0 `WebSocketHandler` requires
  90. applications that wish to receive cross-origin websockets to opt in
  91. by overriding the `~WebSocketHandler.check_origin` method (see that
  92. method's docs for details). Failure to do so is the most likely
  93. cause of 403 errors when making a websocket connection.
  94. When using a secure websocket connection (``wss://``) with a self-signed
  95. certificate, the connection from a browser may fail because it wants
  96. to show the "accept this certificate" dialog but has nowhere to show it.
  97. You must first visit a regular HTML page using the same certificate
  98. to accept it before the websocket connection will succeed.
  99. """
  100. def __init__(self, application, request, **kwargs):
  101. tornado.web.RequestHandler.__init__(self, application, request,
  102. **kwargs)
  103. self.ws_connection = None
  104. self.close_code = None
  105. self.close_reason = None
  106. self.stream = None
  107. self._on_close_called = False
  108. @tornado.web.asynchronous
  109. def get(self, *args, **kwargs):
  110. self.open_args = args
  111. self.open_kwargs = kwargs
  112. # Upgrade header should be present and should be equal to WebSocket
  113. if self.request.headers.get("Upgrade", "").lower() != 'websocket':
  114. self.set_status(400)
  115. log_msg = "Can \"Upgrade\" only to \"WebSocket\"."
  116. self.finish(log_msg)
  117. gen_log.debug(log_msg)
  118. return
  119. # Connection header should be upgrade.
  120. # Some proxy servers/load balancers
  121. # might mess with it.
  122. headers = self.request.headers
  123. connection = map(lambda s: s.strip().lower(),
  124. headers.get("Connection", "").split(","))
  125. if 'upgrade' not in connection:
  126. self.set_status(400)
  127. log_msg = "\"Connection\" must be \"Upgrade\"."
  128. self.finish(log_msg)
  129. gen_log.debug(log_msg)
  130. return
  131. # Handle WebSocket Origin naming convention differences
  132. # The difference between version 8 and 13 is that in 8 the
  133. # client sends a "Sec-Websocket-Origin" header and in 13 it's
  134. # simply "Origin".
  135. if "Origin" in self.request.headers:
  136. origin = self.request.headers.get("Origin")
  137. else:
  138. origin = self.request.headers.get("Sec-Websocket-Origin", None)
  139. # If there was an origin header, check to make sure it matches
  140. # according to check_origin. When the origin is None, we assume it
  141. # did not come from a browser and that it can be passed on.
  142. if origin is not None and not self.check_origin(origin):
  143. self.set_status(403)
  144. log_msg = "Cross origin websockets not allowed"
  145. self.finish(log_msg)
  146. gen_log.debug(log_msg)
  147. return
  148. self.stream = self.request.connection.detach()
  149. self.stream.set_close_callback(self.on_connection_close)
  150. self.ws_connection = self.get_websocket_protocol()
  151. if self.ws_connection:
  152. self.ws_connection.accept_connection()
  153. else:
  154. if not self.stream.closed():
  155. self.stream.write(tornado.escape.utf8(
  156. "HTTP/1.1 426 Upgrade Required\r\n"
  157. "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n"))
  158. self.stream.close()
  159. def write_message(self, message, binary=False):
  160. """Sends the given message to the client of this Web Socket.
  161. The message may be either a string or a dict (which will be
  162. encoded as json). If the ``binary`` argument is false, the
  163. message will be sent as utf8; in binary mode any byte string
  164. is allowed.
  165. If the connection is already closed, raises `WebSocketClosedError`.
  166. .. versionchanged:: 3.2
  167. `WebSocketClosedError` was added (previously a closed connection
  168. would raise an `AttributeError`)
  169. .. versionchanged:: 4.3
  170. Returns a `.Future` which can be used for flow control.
  171. """
  172. if self.ws_connection is None:
  173. raise WebSocketClosedError()
  174. if isinstance(message, dict):
  175. message = tornado.escape.json_encode(message)
  176. return self.ws_connection.write_message(message, binary=binary)
  177. def select_subprotocol(self, subprotocols):
  178. """Invoked when a new WebSocket requests specific subprotocols.
  179. ``subprotocols`` is a list of strings identifying the
  180. subprotocols proposed by the client. This method may be
  181. overridden to return one of those strings to select it, or
  182. ``None`` to not select a subprotocol. Failure to select a
  183. subprotocol does not automatically abort the connection,
  184. although clients may close the connection if none of their
  185. proposed subprotocols was selected.
  186. """
  187. return None
  188. def get_compression_options(self):
  189. """Override to return compression options for the connection.
  190. If this method returns None (the default), compression will
  191. be disabled. If it returns a dict (even an empty one), it
  192. will be enabled. The contents of the dict may be used to
  193. control the memory and CPU usage of the compression,
  194. but no such options are currently implemented.
  195. .. versionadded:: 4.1
  196. """
  197. return None
  198. def open(self, *args, **kwargs):
  199. """Invoked when a new WebSocket is opened.
  200. The arguments to `open` are extracted from the `tornado.web.URLSpec`
  201. regular expression, just like the arguments to
  202. `tornado.web.RequestHandler.get`.
  203. """
  204. pass
  205. def on_message(self, message):
  206. """Handle incoming messages on the WebSocket
  207. This method must be overridden.
  208. """
  209. raise NotImplementedError
  210. def ping(self, data):
  211. """Send ping frame to the remote end."""
  212. if self.ws_connection is None:
  213. raise WebSocketClosedError()
  214. self.ws_connection.write_ping(data)
  215. def on_pong(self, data):
  216. """Invoked when the response to a ping frame is received."""
  217. pass
  218. def on_close(self):
  219. """Invoked when the WebSocket is closed.
  220. If the connection was closed cleanly and a status code or reason
  221. phrase was supplied, these values will be available as the attributes
  222. ``self.close_code`` and ``self.close_reason``.
  223. .. versionchanged:: 4.0
  224. Added ``close_code`` and ``close_reason`` attributes.
  225. """
  226. pass
  227. def close(self, code=None, reason=None):
  228. """Closes this Web Socket.
  229. Once the close handshake is successful the socket will be closed.
  230. ``code`` may be a numeric status code, taken from the values
  231. defined in `RFC 6455 section 7.4.1
  232. <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.
  233. ``reason`` may be a textual message about why the connection is
  234. closing. These values are made available to the client, but are
  235. not otherwise interpreted by the websocket protocol.
  236. .. versionchanged:: 4.0
  237. Added the ``code`` and ``reason`` arguments.
  238. """
  239. if self.ws_connection:
  240. self.ws_connection.close(code, reason)
  241. self.ws_connection = None
  242. def check_origin(self, origin):
  243. """Override to enable support for allowing alternate origins.
  244. The ``origin`` argument is the value of the ``Origin`` HTTP
  245. header, the url responsible for initiating this request. This
  246. method is not called for clients that do not send this header;
  247. such requests are always allowed (because all browsers that
  248. implement WebSockets support this header, and non-browser
  249. clients do not have the same cross-site security concerns).
  250. Should return True to accept the request or False to reject it.
  251. By default, rejects all requests with an origin on a host other
  252. than this one.
  253. This is a security protection against cross site scripting attacks on
  254. browsers, since WebSockets are allowed to bypass the usual same-origin
  255. policies and don't use CORS headers.
  256. To accept all cross-origin traffic (which was the default prior to
  257. Tornado 4.0), simply override this method to always return true::
  258. def check_origin(self, origin):
  259. return True
  260. To allow connections from any subdomain of your site, you might
  261. do something like::
  262. def check_origin(self, origin):
  263. parsed_origin = urllib.parse.urlparse(origin)
  264. return parsed_origin.netloc.endswith(".mydomain.com")
  265. .. versionadded:: 4.0
  266. """
  267. parsed_origin = urlparse(origin)
  268. origin = parsed_origin.netloc
  269. origin = origin.lower()
  270. host = self.request.headers.get("Host")
  271. # Check to see that origin matches host directly, including ports
  272. return origin == host
  273. def set_nodelay(self, value):
  274. """Set the no-delay flag for this stream.
  275. By default, small messages may be delayed and/or combined to minimize
  276. the number of packets sent. This can sometimes cause 200-500ms delays
  277. due to the interaction between Nagle's algorithm and TCP delayed
  278. ACKs. To reduce this delay (at the expense of possibly increasing
  279. bandwidth usage), call ``self.set_nodelay(True)`` once the websocket
  280. connection is established.
  281. See `.BaseIOStream.set_nodelay` for additional details.
  282. .. versionadded:: 3.1
  283. """
  284. self.stream.set_nodelay(value)
  285. def on_connection_close(self):
  286. if self.ws_connection:
  287. self.ws_connection.on_connection_close()
  288. self.ws_connection = None
  289. if not self._on_close_called:
  290. self._on_close_called = True
  291. self.on_close()
  292. def send_error(self, *args, **kwargs):
  293. if self.stream is None:
  294. super(WebSocketHandler, self).send_error(*args, **kwargs)
  295. else:
  296. # If we get an uncaught exception during the handshake,
  297. # we have no choice but to abruptly close the connection.
  298. # TODO: for uncaught exceptions after the handshake,
  299. # we can close the connection more gracefully.
  300. self.stream.close()
  301. def get_websocket_protocol(self):
  302. websocket_version = self.request.headers.get("Sec-WebSocket-Version")
  303. if websocket_version in ("7", "8", "13"):
  304. return WebSocketProtocol13(
  305. self, compression_options=self.get_compression_options())
  306. def _wrap_method(method):
  307. def _disallow_for_websocket(self, *args, **kwargs):
  308. if self.stream is None:
  309. method(self, *args, **kwargs)
  310. else:
  311. raise RuntimeError("Method not supported for Web Sockets")
  312. return _disallow_for_websocket
  313. for method in ["write", "redirect", "set_header", "set_cookie",
  314. "set_status", "flush", "finish"]:
  315. setattr(WebSocketHandler, method,
  316. _wrap_method(getattr(WebSocketHandler, method)))
  317. class WebSocketProtocol(object):
  318. """Base class for WebSocket protocol versions.
  319. """
  320. def __init__(self, handler):
  321. self.handler = handler
  322. self.request = handler.request
  323. self.stream = handler.stream
  324. self.client_terminated = False
  325. self.server_terminated = False
  326. def _run_callback(self, callback, *args, **kwargs):
  327. """Runs the given callback with exception handling.
  328. On error, aborts the websocket connection and returns False.
  329. """
  330. try:
  331. callback(*args, **kwargs)
  332. except Exception:
  333. app_log.error("Uncaught exception in %s",
  334. self.request.path, exc_info=True)
  335. self._abort()
  336. def on_connection_close(self):
  337. self._abort()
  338. def _abort(self):
  339. """Instantly aborts the WebSocket connection by closing the socket"""
  340. self.client_terminated = True
  341. self.server_terminated = True
  342. self.stream.close() # forcibly tear down the connection
  343. self.close() # let the subclass cleanup
  344. class _PerMessageDeflateCompressor(object):
  345. def __init__(self, persistent, max_wbits):
  346. if max_wbits is None:
  347. max_wbits = zlib.MAX_WBITS
  348. # There is no symbolic constant for the minimum wbits value.
  349. if not (8 <= max_wbits <= zlib.MAX_WBITS):
  350. raise ValueError("Invalid max_wbits value %r; allowed range 8-%d",
  351. max_wbits, zlib.MAX_WBITS)
  352. self._max_wbits = max_wbits
  353. if persistent:
  354. self._compressor = self._create_compressor()
  355. else:
  356. self._compressor = None
  357. def _create_compressor(self):
  358. return zlib.compressobj(tornado.web.GZipContentEncoding.GZIP_LEVEL,
  359. zlib.DEFLATED, -self._max_wbits)
  360. def compress(self, data):
  361. compressor = self._compressor or self._create_compressor()
  362. data = (compressor.compress(data) +
  363. compressor.flush(zlib.Z_SYNC_FLUSH))
  364. assert data.endswith(b'\x00\x00\xff\xff')
  365. return data[:-4]
  366. class _PerMessageDeflateDecompressor(object):
  367. def __init__(self, persistent, max_wbits):
  368. if max_wbits is None:
  369. max_wbits = zlib.MAX_WBITS
  370. if not (8 <= max_wbits <= zlib.MAX_WBITS):
  371. raise ValueError("Invalid max_wbits value %r; allowed range 8-%d",
  372. max_wbits, zlib.MAX_WBITS)
  373. self._max_wbits = max_wbits
  374. if persistent:
  375. self._decompressor = self._create_decompressor()
  376. else:
  377. self._decompressor = None
  378. def _create_decompressor(self):
  379. return zlib.decompressobj(-self._max_wbits)
  380. def decompress(self, data):
  381. decompressor = self._decompressor or self._create_decompressor()
  382. return decompressor.decompress(data + b'\x00\x00\xff\xff')
  383. class WebSocketProtocol13(WebSocketProtocol):
  384. """Implementation of the WebSocket protocol from RFC 6455.
  385. This class supports versions 7 and 8 of the protocol in addition to the
  386. final version 13.
  387. """
  388. # Bit masks for the first byte of a frame.
  389. FIN = 0x80
  390. RSV1 = 0x40
  391. RSV2 = 0x20
  392. RSV3 = 0x10
  393. RSV_MASK = RSV1 | RSV2 | RSV3
  394. OPCODE_MASK = 0x0f
  395. def __init__(self, handler, mask_outgoing=False,
  396. compression_options=None):
  397. WebSocketProtocol.__init__(self, handler)
  398. self.mask_outgoing = mask_outgoing
  399. self._final_frame = False
  400. self._frame_opcode = None
  401. self._masked_frame = None
  402. self._frame_mask = None
  403. self._frame_length = None
  404. self._fragmented_message_buffer = None
  405. self._fragmented_message_opcode = None
  406. self._waiting = None
  407. self._compression_options = compression_options
  408. self._decompressor = None
  409. self._compressor = None
  410. self._frame_compressed = None
  411. # The total uncompressed size of all messages received or sent.
  412. # Unicode messages are encoded to utf8.
  413. # Only for testing; subject to change.
  414. self._message_bytes_in = 0
  415. self._message_bytes_out = 0
  416. # The total size of all packets received or sent. Includes
  417. # the effect of compression, frame overhead, and control frames.
  418. self._wire_bytes_in = 0
  419. self._wire_bytes_out = 0
  420. def accept_connection(self):
  421. try:
  422. self._handle_websocket_headers()
  423. self._accept_connection()
  424. except ValueError:
  425. gen_log.debug("Malformed WebSocket request received",
  426. exc_info=True)
  427. self._abort()
  428. return
  429. def _handle_websocket_headers(self):
  430. """Verifies all invariant- and required headers
  431. If a header is missing or have an incorrect value ValueError will be
  432. raised
  433. """
  434. fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version")
  435. if not all(map(lambda f: self.request.headers.get(f), fields)):
  436. raise ValueError("Missing/Invalid WebSocket headers")
  437. @staticmethod
  438. def compute_accept_value(key):
  439. """Computes the value for the Sec-WebSocket-Accept header,
  440. given the value for Sec-WebSocket-Key.
  441. """
  442. sha1 = hashlib.sha1()
  443. sha1.update(utf8(key))
  444. sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") # Magic value
  445. return native_str(base64.b64encode(sha1.digest()))
  446. def _challenge_response(self):
  447. return WebSocketProtocol13.compute_accept_value(
  448. self.request.headers.get("Sec-Websocket-Key"))
  449. def _accept_connection(self):
  450. subprotocol_header = ''
  451. subprotocols = self.request.headers.get("Sec-WebSocket-Protocol", '')
  452. subprotocols = [s.strip() for s in subprotocols.split(',')]
  453. if subprotocols:
  454. selected = self.handler.select_subprotocol(subprotocols)
  455. if selected:
  456. assert selected in subprotocols
  457. subprotocol_header = ("Sec-WebSocket-Protocol: %s\r\n"
  458. % selected)
  459. extension_header = ''
  460. extensions = self._parse_extensions_header(self.request.headers)
  461. for ext in extensions:
  462. if (ext[0] == 'permessage-deflate' and
  463. self._compression_options is not None):
  464. # TODO: negotiate parameters if compression_options
  465. # specifies limits.
  466. self._create_compressors('server', ext[1])
  467. if ('client_max_window_bits' in ext[1] and
  468. ext[1]['client_max_window_bits'] is None):
  469. # Don't echo an offered client_max_window_bits
  470. # parameter with no value.
  471. del ext[1]['client_max_window_bits']
  472. extension_header = ('Sec-WebSocket-Extensions: %s\r\n' %
  473. httputil._encode_header(
  474. 'permessage-deflate', ext[1]))
  475. break
  476. if self.stream.closed():
  477. self._abort()
  478. return
  479. self.stream.write(tornado.escape.utf8(
  480. "HTTP/1.1 101 Switching Protocols\r\n"
  481. "Upgrade: websocket\r\n"
  482. "Connection: Upgrade\r\n"
  483. "Sec-WebSocket-Accept: %s\r\n"
  484. "%s%s"
  485. "\r\n" % (self._challenge_response(),
  486. subprotocol_header, extension_header)))
  487. self._run_callback(self.handler.open, *self.handler.open_args,
  488. **self.handler.open_kwargs)
  489. self._receive_frame()
  490. def _parse_extensions_header(self, headers):
  491. extensions = headers.get("Sec-WebSocket-Extensions", '')
  492. if extensions:
  493. return [httputil._parse_header(e.strip())
  494. for e in extensions.split(',')]
  495. return []
  496. def _process_server_headers(self, key, headers):
  497. """Process the headers sent by the server to this client connection.
  498. 'key' is the websocket handshake challenge/response key.
  499. """
  500. assert headers['Upgrade'].lower() == 'websocket'
  501. assert headers['Connection'].lower() == 'upgrade'
  502. accept = self.compute_accept_value(key)
  503. assert headers['Sec-Websocket-Accept'] == accept
  504. extensions = self._parse_extensions_header(headers)
  505. for ext in extensions:
  506. if (ext[0] == 'permessage-deflate' and
  507. self._compression_options is not None):
  508. self._create_compressors('client', ext[1])
  509. else:
  510. raise ValueError("unsupported extension %r", ext)
  511. def _get_compressor_options(self, side, agreed_parameters):
  512. """Converts a websocket agreed_parameters set to keyword arguments
  513. for our compressor objects.
  514. """
  515. options = dict(
  516. persistent=(side + '_no_context_takeover') not in agreed_parameters)
  517. wbits_header = agreed_parameters.get(side + '_max_window_bits', None)
  518. if wbits_header is None:
  519. options['max_wbits'] = zlib.MAX_WBITS
  520. else:
  521. options['max_wbits'] = int(wbits_header)
  522. return options
  523. def _create_compressors(self, side, agreed_parameters):
  524. # TODO: handle invalid parameters gracefully
  525. allowed_keys = set(['server_no_context_takeover',
  526. 'client_no_context_takeover',
  527. 'server_max_window_bits',
  528. 'client_max_window_bits'])
  529. for key in agreed_parameters:
  530. if key not in allowed_keys:
  531. raise ValueError("unsupported compression parameter %r" % key)
  532. other_side = 'client' if (side == 'server') else 'server'
  533. self._compressor = _PerMessageDeflateCompressor(
  534. **self._get_compressor_options(side, agreed_parameters))
  535. self._decompressor = _PerMessageDeflateDecompressor(
  536. **self._get_compressor_options(other_side, agreed_parameters))
  537. def _write_frame(self, fin, opcode, data, flags=0):
  538. if fin:
  539. finbit = self.FIN
  540. else:
  541. finbit = 0
  542. frame = struct.pack("B", finbit | opcode | flags)
  543. l = len(data)
  544. if self.mask_outgoing:
  545. mask_bit = 0x80
  546. else:
  547. mask_bit = 0
  548. if l < 126:
  549. frame += struct.pack("B", l | mask_bit)
  550. elif l <= 0xFFFF:
  551. frame += struct.pack("!BH", 126 | mask_bit, l)
  552. else:
  553. frame += struct.pack("!BQ", 127 | mask_bit, l)
  554. if self.mask_outgoing:
  555. mask = os.urandom(4)
  556. data = mask + _websocket_mask(mask, data)
  557. frame += data
  558. self._wire_bytes_out += len(frame)
  559. try:
  560. return self.stream.write(frame)
  561. except StreamClosedError:
  562. self._abort()
  563. def write_message(self, message, binary=False):
  564. """Sends the given message to the client of this Web Socket."""
  565. if binary:
  566. opcode = 0x2
  567. else:
  568. opcode = 0x1
  569. message = tornado.escape.utf8(message)
  570. assert isinstance(message, bytes)
  571. self._message_bytes_out += len(message)
  572. flags = 0
  573. if self._compressor:
  574. message = self._compressor.compress(message)
  575. flags |= self.RSV1
  576. return self._write_frame(True, opcode, message, flags=flags)
  577. def write_ping(self, data):
  578. """Send ping frame."""
  579. assert isinstance(data, bytes)
  580. self._write_frame(True, 0x9, data)
  581. def _receive_frame(self):
  582. try:
  583. self.stream.read_bytes(2, self._on_frame_start)
  584. except StreamClosedError:
  585. self._abort()
  586. def _on_frame_start(self, data):
  587. self._wire_bytes_in += len(data)
  588. header, payloadlen = struct.unpack("BB", data)
  589. self._final_frame = header & self.FIN
  590. reserved_bits = header & self.RSV_MASK
  591. self._frame_opcode = header & self.OPCODE_MASK
  592. self._frame_opcode_is_control = self._frame_opcode & 0x8
  593. if self._decompressor is not None and self._frame_opcode != 0:
  594. self._frame_compressed = bool(reserved_bits & self.RSV1)
  595. reserved_bits &= ~self.RSV1
  596. if reserved_bits:
  597. # client is using as-yet-undefined extensions; abort
  598. self._abort()
  599. return
  600. self._masked_frame = bool(payloadlen & 0x80)
  601. payloadlen = payloadlen & 0x7f
  602. if self._frame_opcode_is_control and payloadlen >= 126:
  603. # control frames must have payload < 126
  604. self._abort()
  605. return
  606. try:
  607. if payloadlen < 126:
  608. self._frame_length = payloadlen
  609. if self._masked_frame:
  610. self.stream.read_bytes(4, self._on_masking_key)
  611. else:
  612. self.stream.read_bytes(self._frame_length,
  613. self._on_frame_data)
  614. elif payloadlen == 126:
  615. self.stream.read_bytes(2, self._on_frame_length_16)
  616. elif payloadlen == 127:
  617. self.stream.read_bytes(8, self._on_frame_length_64)
  618. except StreamClosedError:
  619. self._abort()
  620. def _on_frame_length_16(self, data):
  621. self._wire_bytes_in += len(data)
  622. self._frame_length = struct.unpack("!H", data)[0]
  623. try:
  624. if self._masked_frame:
  625. self.stream.read_bytes(4, self._on_masking_key)
  626. else:
  627. self.stream.read_bytes(self._frame_length, self._on_frame_data)
  628. except StreamClosedError:
  629. self._abort()
  630. def _on_frame_length_64(self, data):
  631. self._wire_bytes_in += len(data)
  632. self._frame_length = struct.unpack("!Q", data)[0]
  633. try:
  634. if self._masked_frame:
  635. self.stream.read_bytes(4, self._on_masking_key)
  636. else:
  637. self.stream.read_bytes(self._frame_length, self._on_frame_data)
  638. except StreamClosedError:
  639. self._abort()
  640. def _on_masking_key(self, data):
  641. self._wire_bytes_in += len(data)
  642. self._frame_mask = data
  643. try:
  644. self.stream.read_bytes(self._frame_length,
  645. self._on_masked_frame_data)
  646. except StreamClosedError:
  647. self._abort()
  648. def _on_masked_frame_data(self, data):
  649. # Don't touch _wire_bytes_in; we'll do it in _on_frame_data.
  650. self._on_frame_data(_websocket_mask(self._frame_mask, data))
  651. def _on_frame_data(self, data):
  652. self._wire_bytes_in += len(data)
  653. if self._frame_opcode_is_control:
  654. # control frames may be interleaved with a series of fragmented
  655. # data frames, so control frames must not interact with
  656. # self._fragmented_*
  657. if not self._final_frame:
  658. # control frames must not be fragmented
  659. self._abort()
  660. return
  661. opcode = self._frame_opcode
  662. elif self._frame_opcode == 0: # continuation frame
  663. if self._fragmented_message_buffer is None:
  664. # nothing to continue
  665. self._abort()
  666. return
  667. self._fragmented_message_buffer += data
  668. if self._final_frame:
  669. opcode = self._fragmented_message_opcode
  670. data = self._fragmented_message_buffer
  671. self._fragmented_message_buffer = None
  672. else: # start of new data message
  673. if self._fragmented_message_buffer is not None:
  674. # can't start new message until the old one is finished
  675. self._abort()
  676. return
  677. if self._final_frame:
  678. opcode = self._frame_opcode
  679. else:
  680. self._fragmented_message_opcode = self._frame_opcode
  681. self._fragmented_message_buffer = data
  682. if self._final_frame:
  683. self._handle_message(opcode, data)
  684. if not self.client_terminated:
  685. self._receive_frame()
  686. def _handle_message(self, opcode, data):
  687. if self.client_terminated:
  688. return
  689. if self._frame_compressed:
  690. data = self._decompressor.decompress(data)
  691. if opcode == 0x1:
  692. # UTF-8 data
  693. self._message_bytes_in += len(data)
  694. try:
  695. decoded = data.decode("utf-8")
  696. except UnicodeDecodeError:
  697. self._abort()
  698. return
  699. self._run_callback(self.handler.on_message, decoded)
  700. elif opcode == 0x2:
  701. # Binary data
  702. self._message_bytes_in += len(data)
  703. self._run_callback(self.handler.on_message, data)
  704. elif opcode == 0x8:
  705. # Close
  706. self.client_terminated = True
  707. if len(data) >= 2:
  708. self.handler.close_code = struct.unpack('>H', data[:2])[0]
  709. if len(data) > 2:
  710. self.handler.close_reason = to_unicode(data[2:])
  711. # Echo the received close code, if any (RFC 6455 section 5.5.1).
  712. self.close(self.handler.close_code)
  713. elif opcode == 0x9:
  714. # Ping
  715. self._write_frame(True, 0xA, data)
  716. elif opcode == 0xA:
  717. # Pong
  718. self._run_callback(self.handler.on_pong, data)
  719. else:
  720. self._abort()
  721. def close(self, code=None, reason=None):
  722. """Closes the WebSocket connection."""
  723. if not self.server_terminated:
  724. if not self.stream.closed():
  725. if code is None and reason is not None:
  726. code = 1000 # "normal closure" status code
  727. if code is None:
  728. close_data = b''
  729. else:
  730. close_data = struct.pack('>H', code)
  731. if reason is not None:
  732. close_data += utf8(reason)
  733. self._write_frame(True, 0x8, close_data)
  734. self.server_terminated = True
  735. if self.client_terminated:
  736. if self._waiting is not None:
  737. self.stream.io_loop.remove_timeout(self._waiting)
  738. self._waiting = None
  739. self.stream.close()
  740. elif self._waiting is None:
  741. # Give the client a few seconds to complete a clean shutdown,
  742. # otherwise just close the connection.
  743. self._waiting = self.stream.io_loop.add_timeout(
  744. self.stream.io_loop.time() + 5, self._abort)
  745. class WebSocketClientConnection(simple_httpclient._HTTPConnection):
  746. """WebSocket client connection.
  747. This class should not be instantiated directly; use the
  748. `websocket_connect` function instead.
  749. """
  750. def __init__(self, io_loop, request, on_message_callback=None,
  751. compression_options=None):
  752. self.compression_options = compression_options
  753. self.connect_future = TracebackFuture()
  754. self.protocol = None
  755. self.read_future = None
  756. self.read_queue = collections.deque()
  757. self.key = base64.b64encode(os.urandom(16))
  758. self._on_message_callback = on_message_callback
  759. self.close_code = self.close_reason = None
  760. scheme, sep, rest = request.url.partition(':')
  761. scheme = {'ws': 'http', 'wss': 'https'}[scheme]
  762. request.url = scheme + sep + rest
  763. request.headers.update({
  764. 'Upgrade': 'websocket',
  765. 'Connection': 'Upgrade',
  766. 'Sec-WebSocket-Key': self.key,
  767. 'Sec-WebSocket-Version': '13',
  768. })
  769. if self.compression_options is not None:
  770. # Always offer to let the server set our max_wbits (and even though
  771. # we don't offer it, we will accept a client_no_context_takeover
  772. # from the server).
  773. # TODO: set server parameters for deflate extension
  774. # if requested in self.compression_options.
  775. request.headers['Sec-WebSocket-Extensions'] = (
  776. 'permessage-deflate; client_max_window_bits')
  777. self.tcp_client = TCPClient(io_loop=io_loop)
  778. super(WebSocketClientConnection, self).__init__(
  779. io_loop, None, request, lambda: None, self._on_http_response,
  780. 104857600, self.tcp_client, 65536, 104857600)
  781. def close(self, code=None, reason=None):
  782. """Closes the websocket connection.
  783. ``code`` and ``reason`` are documented under
  784. `WebSocketHandler.close`.
  785. .. versionadded:: 3.2
  786. .. versionchanged:: 4.0
  787. Added the ``code`` and ``reason`` arguments.
  788. """
  789. if self.protocol is not None:
  790. self.protocol.close(code, reason)
  791. self.protocol = None
  792. def on_connection_close(self):
  793. if not self.connect_future.done():
  794. self.connect_future.set_exception(StreamClosedError())
  795. self.on_message(None)
  796. self.tcp_client.close()
  797. super(WebSocketClientConnection, self).on_connection_close()
  798. def _on_http_response(self, response):
  799. if not self.connect_future.done():
  800. if response.error:
  801. self.connect_future.set_exception(response.error)
  802. else:
  803. self.connect_future.set_exception(WebSocketError(
  804. "Non-websocket response"))
  805. def headers_received(self, start_line, headers):
  806. if start_line.code != 101:
  807. return super(WebSocketClientConnection, self).headers_received(
  808. start_line, headers)
  809. self.headers = headers
  810. self.protocol = self.get_websocket_protocol()
  811. self.protocol._process_server_headers(self.key, self.headers)
  812. self.protocol._receive_frame()
  813. if self._timeout is not None:
  814. self.io_loop.remove_timeout(self._timeout)
  815. self._timeout = None
  816. self.stream = self.connection.detach()
  817. self.stream.set_close_callback(self.on_connection_close)
  818. # Once we've taken over the connection, clear the final callback
  819. # we set on the http request. This deactivates the error handling
  820. # in simple_httpclient that would otherwise interfere with our
  821. # ability to see exceptions.
  822. self.final_callback = None
  823. self.connect_future.set_result(self)
  824. def write_message(self, message, binary=False):
  825. """Sends a message to the WebSocket server."""
  826. return self.protocol.write_message(message, binary)
  827. def read_message(self, callback=None):
  828. """Reads a message from the WebSocket server.
  829. If on_message_callback was specified at WebSocket
  830. initialization, this function will never return messages
  831. Returns a future whose result is the message, or None
  832. if the connection is closed. If a callback argument
  833. is given it will be called with the future when it is
  834. ready.
  835. """
  836. assert self.read_future is None
  837. future = TracebackFuture()
  838. if self.read_queue:
  839. future.set_result(self.read_queue.popleft())
  840. else:
  841. self.read_future = future
  842. if callback is not None:
  843. self.io_loop.add_future(future, callback)
  844. return future
  845. def on_message(self, message):
  846. if self._on_message_callback:
  847. self._on_message_callback(message)
  848. elif self.read_future is not None:
  849. self.read_future.set_result(message)
  850. self.read_future = None
  851. else:
  852. self.read_queue.append(message)
  853. def on_pong(self, data):
  854. pass
  855. def get_websocket_protocol(self):
  856. return WebSocketProtocol13(self, mask_outgoing=True,
  857. compression_options=self.compression_options)
  858. def websocket_connect(url, io_loop=None, callback=None, connect_timeout=None,
  859. on_message_callback=None, compression_options=None):
  860. """Client-side websocket support.
  861. Takes a url and returns a Future whose result is a
  862. `WebSocketClientConnection`.
  863. ``compression_options`` is interpreted in the same way as the
  864. return value of `.WebSocketHandler.get_compression_options`.
  865. The connection supports two styles of operation. In the coroutine
  866. style, the application typically calls
  867. `~.WebSocketClientConnection.read_message` in a loop::
  868. conn = yield websocket_connect(url)
  869. while True:
  870. msg = yield conn.read_message()
  871. if msg is None: break
  872. # Do something with msg
  873. In the callback style, pass an ``on_message_callback`` to
  874. ``websocket_connect``. In both styles, a message of ``None``
  875. indicates that the connection has been closed.
  876. .. versionchanged:: 3.2
  877. Also accepts ``HTTPRequest`` objects in place of urls.
  878. .. versionchanged:: 4.1
  879. Added ``compression_options`` and ``on_message_callback``.
  880. The ``io_loop`` argument is deprecated.
  881. """
  882. if io_loop is None:
  883. io_loop = IOLoop.current()
  884. if isinstance(url, httpclient.HTTPRequest):
  885. assert connect_timeout is None
  886. request = url
  887. # Copy and convert the headers dict/object (see comments in
  888. # AsyncHTTPClient.fetch)
  889. request.headers = httputil.HTTPHeaders(request.headers)
  890. else:
  891. request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)
  892. request = httpclient._RequestProxy(
  893. request, httpclient.HTTPRequest._DEFAULTS)
  894. conn = WebSocketClientConnection(io_loop, request,
  895. on_message_callback=on_message_callback,
  896. compression_options=compression_options)
  897. if callback is not None:
  898. io_loop.add_future(conn.connect_future, callback)
  899. return conn.connect_future