websock.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Websock: high-performance binary WebSockets
  3. * Copyright (C) 2012 Joel Martin
  4. * Licensed under MPL 2.0 (see LICENSE.txt)
  5. *
  6. * Websock is similar to the standard WebSocket object but Websock
  7. * enables communication with raw TCP sockets (i.e. the binary stream)
  8. * via websockify. This is accomplished by base64 encoding the data
  9. * stream between Websock and websockify.
  10. *
  11. * Websock has built-in receive queue buffering; the message event
  12. * does not contain actual data but is simply a notification that
  13. * there is new data available. Several rQ* methods are available to
  14. * read binary data off of the receive queue.
  15. */
  16. /*jslint browser: true, bitwise: true */
  17. /*global Util*/
  18. // Load Flash WebSocket emulator if needed
  19. // To force WebSocket emulator even when native WebSocket available
  20. //window.WEB_SOCKET_FORCE_FLASH = true;
  21. // To enable WebSocket emulator debug:
  22. //window.WEB_SOCKET_DEBUG=1;
  23. if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) {
  24. Websock_native = true;
  25. } else if (window.MozWebSocket && !window.WEB_SOCKET_FORCE_FLASH) {
  26. Websock_native = true;
  27. window.WebSocket = window.MozWebSocket;
  28. } else {
  29. /* no builtin WebSocket so load web_socket.js */
  30. Websock_native = false;
  31. }
  32. function Websock() {
  33. "use strict";
  34. this._websocket = null; // WebSocket object
  35. this._rQi = 0; // Receive queue index
  36. this._rQlen = 0; // Next write position in the receive queue
  37. this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
  38. this._rQmax = this._rQbufferSize / 8;
  39. // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
  40. this._rQ = null; // Receive queue
  41. this._sQbufferSize = 1024 * 10; // 10 KiB
  42. // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
  43. this._sQlen = 0;
  44. this._sQ = null; // Send queue
  45. this._mode = 'binary'; // Current WebSocket mode: 'binary', 'base64'
  46. this.maxBufferedAmount = 200;
  47. this._eventHandlers = {
  48. 'message': function () {},
  49. 'open': function () {},
  50. 'close': function () {},
  51. 'error': function () {}
  52. };
  53. }
  54. (function () {
  55. "use strict";
  56. // this has performance issues in some versions Chromium, and
  57. // doesn't gain a tremendous amount of performance increase in Firefox
  58. // at the moment. It may be valuable to turn it on in the future.
  59. var ENABLE_COPYWITHIN = false;
  60. var typedArrayToString = (function () {
  61. // This is only for PhantomJS, which doesn't like apply-ing
  62. // with Typed Arrays
  63. try {
  64. var arr = new Uint8Array([1, 2, 3]);
  65. String.fromCharCode.apply(null, arr);
  66. return function (a) { return String.fromCharCode.apply(null, a); };
  67. } catch (ex) {
  68. return function (a) {
  69. return String.fromCharCode.apply(
  70. null, Array.prototype.slice.call(a));
  71. };
  72. }
  73. })();
  74. Websock.prototype = {
  75. // Getters and Setters
  76. get_sQ: function () {
  77. return this._sQ;
  78. },
  79. get_rQ: function () {
  80. return this._rQ;
  81. },
  82. get_rQi: function () {
  83. return this._rQi;
  84. },
  85. set_rQi: function (val) {
  86. this._rQi = val;
  87. },
  88. // Receive Queue
  89. rQlen: function () {
  90. return this._rQlen - this._rQi;
  91. },
  92. rQpeek8: function () {
  93. return this._rQ[this._rQi];
  94. },
  95. rQshift8: function () {
  96. return this._rQ[this._rQi++];
  97. },
  98. rQskip8: function () {
  99. this._rQi++;
  100. },
  101. rQskipBytes: function (num) {
  102. this._rQi += num;
  103. },
  104. // TODO(directxman12): test performance with these vs a DataView
  105. rQshift16: function () {
  106. return (this._rQ[this._rQi++] << 8) +
  107. this._rQ[this._rQi++];
  108. },
  109. rQshift32: function () {
  110. return (this._rQ[this._rQi++] << 24) +
  111. (this._rQ[this._rQi++] << 16) +
  112. (this._rQ[this._rQi++] << 8) +
  113. this._rQ[this._rQi++];
  114. },
  115. rQshiftStr: function (len) {
  116. if (typeof(len) === 'undefined') { len = this.rQlen(); }
  117. var arr = new Uint8Array(this._rQ.buffer, this._rQi, len);
  118. this._rQi += len;
  119. return typedArrayToString(arr);
  120. },
  121. rQshiftBytes: function (len) {
  122. if (typeof(len) === 'undefined') { len = this.rQlen(); }
  123. this._rQi += len;
  124. return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
  125. },
  126. rQshiftTo: function (target, len) {
  127. if (len === undefined) { len = this.rQlen(); }
  128. // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
  129. target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
  130. this._rQi += len;
  131. },
  132. rQwhole: function () {
  133. return new Uint8Array(this._rQ.buffer, 0, this._rQlen);
  134. },
  135. rQslice: function (start, end) {
  136. if (end) {
  137. return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
  138. } else {
  139. return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start);
  140. }
  141. },
  142. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  143. // to be available in the receive queue. Return true if we need to
  144. // wait (and possibly print a debug message), otherwise false.
  145. rQwait: function (msg, num, goback) {
  146. var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
  147. if (rQlen < num) {
  148. if (goback) {
  149. if (this._rQi < goback) {
  150. throw new Error("rQwait cannot backup " + goback + " bytes");
  151. }
  152. this._rQi -= goback;
  153. }
  154. return true; // true means need more data
  155. }
  156. return false;
  157. },
  158. // Send Queue
  159. flush: function () {
  160. if (this._websocket.bufferedAmount !== 0) {
  161. Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount);
  162. }
  163. if (this._websocket.bufferedAmount < this.maxBufferedAmount) {
  164. if (this._sQlen > 0) {
  165. this._websocket.send(this._encode_message());
  166. this._sQlen = 0;
  167. }
  168. return true;
  169. } else {
  170. Util.Info("Delaying send, bufferedAmount: " +
  171. this._websocket.bufferedAmount);
  172. return false;
  173. }
  174. },
  175. send: function (arr) {
  176. this._sQ.set(arr, this._sQlen);
  177. this._sQlen += arr.length;
  178. return this.flush();
  179. },
  180. send_string: function (str) {
  181. this.send(str.split('').map(function (chr) {
  182. return chr.charCodeAt(0);
  183. }));
  184. },
  185. // Event Handlers
  186. off: function (evt) {
  187. this._eventHandlers[evt] = function () {};
  188. },
  189. on: function (evt, handler) {
  190. this._eventHandlers[evt] = handler;
  191. },
  192. _allocate_buffers: function () {
  193. this._rQ = new Uint8Array(this._rQbufferSize);
  194. this._sQ = new Uint8Array(this._sQbufferSize);
  195. },
  196. init: function (protocols, ws_schema) {
  197. this._allocate_buffers();
  198. this._rQi = 0;
  199. this._websocket = null;
  200. // Check for full typed array support
  201. var bt = false;
  202. if (('Uint8Array' in window) &&
  203. ('set' in Uint8Array.prototype)) {
  204. bt = true;
  205. }
  206. // Check for full binary type support in WebSockets
  207. // Inspired by:
  208. // https://github.com/Modernizr/Modernizr/issues/370
  209. // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js
  210. var wsbt = false;
  211. try {
  212. if (bt && ('binaryType' in WebSocket.prototype ||
  213. !!(new WebSocket(ws_schema + '://.').binaryType))) {
  214. Util.Info("Detected binaryType support in WebSockets");
  215. wsbt = true;
  216. }
  217. } catch (exc) {
  218. // Just ignore failed test localhost connection
  219. }
  220. // Default protocols if not specified
  221. if (typeof(protocols) === "undefined") {
  222. protocols = 'binary';
  223. }
  224. if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) {
  225. protocols = 'binary';
  226. }
  227. if (!wsbt) {
  228. throw new Error("noVNC no longer supports base64 WebSockets. " +
  229. "Please use a browser which supports binary WebSockets.");
  230. }
  231. if (protocols != 'binary') {
  232. throw new Error("noVNC no longer supports base64 WebSockets. Please " +
  233. "use the binary subprotocol instead.");
  234. }
  235. return protocols;
  236. },
  237. open: function (uri, protocols) {
  238. var ws_schema = uri.match(/^([a-z]+):\/\//)[1];
  239. protocols = this.init(protocols, ws_schema);
  240. this._websocket = new WebSocket(uri, protocols);
  241. if (protocols.indexOf('binary') >= 0) {
  242. this._websocket.binaryType = 'arraybuffer';
  243. }
  244. this._websocket.onmessage = this._recv_message.bind(this);
  245. this._websocket.onopen = (function () {
  246. Util.Debug('>> WebSock.onopen');
  247. if (this._websocket.protocol) {
  248. this._mode = this._websocket.protocol;
  249. Util.Info("Server choose sub-protocol: " + this._websocket.protocol);
  250. } else {
  251. this._mode = 'binary';
  252. Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol);
  253. }
  254. if (this._mode != 'binary') {
  255. throw new Error("noVNC no longer supports base64 WebSockets. Please " +
  256. "use the binary subprotocol instead.");
  257. }
  258. this._eventHandlers.open();
  259. Util.Debug("<< WebSock.onopen");
  260. }).bind(this);
  261. this._websocket.onclose = (function (e) {
  262. Util.Debug(">> WebSock.onclose");
  263. this._eventHandlers.close(e);
  264. Util.Debug("<< WebSock.onclose");
  265. }).bind(this);
  266. this._websocket.onerror = (function (e) {
  267. Util.Debug(">> WebSock.onerror: " + e);
  268. this._eventHandlers.error(e);
  269. Util.Debug("<< WebSock.onerror: " + e);
  270. }).bind(this);
  271. },
  272. close: function () {
  273. if (this._websocket) {
  274. if ((this._websocket.readyState === WebSocket.OPEN) ||
  275. (this._websocket.readyState === WebSocket.CONNECTING)) {
  276. Util.Info("Closing WebSocket connection");
  277. this._websocket.close();
  278. }
  279. this._websocket.onmessage = function (e) { return; };
  280. }
  281. },
  282. // private methods
  283. _encode_message: function () {
  284. // Put in a binary arraybuffer
  285. // according to the spec, you can send ArrayBufferViews with the send method
  286. return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
  287. },
  288. _decode_message: function (data) {
  289. // push arraybuffer values onto the end
  290. var u8 = new Uint8Array(data);
  291. this._rQ.set(u8, this._rQlen);
  292. this._rQlen += u8.length;
  293. },
  294. _recv_message: function (e) {
  295. try {
  296. this._decode_message(e.data);
  297. if (this.rQlen() > 0) {
  298. this._eventHandlers.message();
  299. // Compact the receive queue
  300. if (this._rQlen == this._rQi) {
  301. this._rQlen = 0;
  302. this._rQi = 0;
  303. } else if (this._rQlen > this._rQmax) {
  304. if (this._rQlen - this._rQi > 0.5 * this._rQbufferSize) {
  305. var old_rQbuffer = this._rQ.buffer;
  306. this._rQbufferSize *= 2;
  307. this._rQmax = this._rQbufferSize / 8;
  308. this._rQ = new Uint8Array(this._rQbufferSize);
  309. this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
  310. } else {
  311. if (ENABLE_COPYWITHIN) {
  312. this._rQ.copyWithin(0, this._rQi);
  313. } else {
  314. this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
  315. }
  316. }
  317. this._rQlen = this._rQlen - this._rQi;
  318. this._rQi = 0;
  319. }
  320. } else {
  321. Util.Debug("Ignoring empty message");
  322. }
  323. } catch (exc) {
  324. var exception_str = "";
  325. if (exc.name) {
  326. exception_str += "\n name: " + exc.name + "\n";
  327. exception_str += " message: " + exc.message + "\n";
  328. }
  329. if (typeof exc.description !== 'undefined') {
  330. exception_str += " description: " + exc.description + "\n";
  331. }
  332. if (typeof exc.stack !== 'undefined') {
  333. exception_str += exc.stack;
  334. }
  335. if (exception_str.length > 0) {
  336. Util.Error("recv_message, caught exception: " + exception_str);
  337. } else {
  338. Util.Error("recv_message, caught exception: " + exc);
  339. }
  340. if (typeof exc.name !== 'undefined') {
  341. this._eventHandlers.error(exc.name + ": " + exc.message);
  342. } else {
  343. this._eventHandlers.error(exc);
  344. }
  345. }
  346. }
  347. };
  348. })();