websock.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
  61. var typedArrayToString = (function () {
  62. // This is only for PhantomJS, which doesn't like apply-ing
  63. // with Typed Arrays
  64. try {
  65. var arr = new Uint8Array([1, 2, 3]);
  66. String.fromCharCode.apply(null, arr);
  67. return function (a) { return String.fromCharCode.apply(null, a); };
  68. } catch (ex) {
  69. return function (a) {
  70. return String.fromCharCode.apply(
  71. null, Array.prototype.slice.call(a));
  72. };
  73. }
  74. })();
  75. Websock.prototype = {
  76. // Getters and Setters
  77. get_sQ: function () {
  78. return this._sQ;
  79. },
  80. get_rQ: function () {
  81. return this._rQ;
  82. },
  83. get_rQi: function () {
  84. return this._rQi;
  85. },
  86. set_rQi: function (val) {
  87. this._rQi = val;
  88. },
  89. // Receive Queue
  90. rQlen: function () {
  91. return this._rQlen - this._rQi;
  92. },
  93. rQpeek8: function () {
  94. return this._rQ[this._rQi];
  95. },
  96. rQshift8: function () {
  97. return this._rQ[this._rQi++];
  98. },
  99. rQskip8: function () {
  100. this._rQi++;
  101. },
  102. rQskipBytes: function (num) {
  103. this._rQi += num;
  104. },
  105. // TODO(directxman12): test performance with these vs a DataView
  106. rQshift16: function () {
  107. return (this._rQ[this._rQi++] << 8) +
  108. this._rQ[this._rQi++];
  109. },
  110. rQshift32: function () {
  111. return (this._rQ[this._rQi++] << 24) +
  112. (this._rQ[this._rQi++] << 16) +
  113. (this._rQ[this._rQi++] << 8) +
  114. this._rQ[this._rQi++];
  115. },
  116. rQshiftStr: function (len) {
  117. if (typeof(len) === 'undefined') { len = this.rQlen(); }
  118. var arr = new Uint8Array(this._rQ.buffer, this._rQi, len);
  119. this._rQi += len;
  120. return typedArrayToString(arr);
  121. },
  122. rQshiftBytes: function (len) {
  123. if (typeof(len) === 'undefined') { len = this.rQlen(); }
  124. this._rQi += len;
  125. return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
  126. },
  127. rQshiftTo: function (target, len) {
  128. if (len === undefined) { len = this.rQlen(); }
  129. // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
  130. target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
  131. this._rQi += len;
  132. },
  133. rQwhole: function () {
  134. return new Uint8Array(this._rQ.buffer, 0, this._rQlen);
  135. },
  136. rQslice: function (start, end) {
  137. if (end) {
  138. return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
  139. } else {
  140. return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start);
  141. }
  142. },
  143. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  144. // to be available in the receive queue. Return true if we need to
  145. // wait (and possibly print a debug message), otherwise false.
  146. rQwait: function (msg, num, goback) {
  147. var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
  148. if (rQlen < num) {
  149. if (goback) {
  150. if (this._rQi < goback) {
  151. throw new Error("rQwait cannot backup " + goback + " bytes");
  152. }
  153. this._rQi -= goback;
  154. }
  155. return true; // true means need more data
  156. }
  157. return false;
  158. },
  159. // Send Queue
  160. flush: function () {
  161. if (this._websocket.bufferedAmount !== 0) {
  162. Util.Debug("bufferedAmount: " + this._websocket.bufferedAmount);
  163. }
  164. if (this._websocket.bufferedAmount < this.maxBufferedAmount) {
  165. if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
  166. this._websocket.send(this._encode_message());
  167. this._sQlen = 0;
  168. }
  169. return true;
  170. } else {
  171. Util.Info("Delaying send, bufferedAmount: " +
  172. this._websocket.bufferedAmount);
  173. return false;
  174. }
  175. },
  176. send: function (arr) {
  177. this._sQ.set(arr, this._sQlen);
  178. this._sQlen += arr.length;
  179. return this.flush();
  180. },
  181. send_string: function (str) {
  182. this.send(str.split('').map(function (chr) {
  183. return chr.charCodeAt(0);
  184. }));
  185. },
  186. // Event Handlers
  187. off: function (evt) {
  188. this._eventHandlers[evt] = function () {};
  189. },
  190. on: function (evt, handler) {
  191. this._eventHandlers[evt] = handler;
  192. },
  193. _allocate_buffers: function () {
  194. this._rQ = new Uint8Array(this._rQbufferSize);
  195. this._sQ = new Uint8Array(this._sQbufferSize);
  196. },
  197. init: function (protocols, ws_schema) {
  198. this._allocate_buffers();
  199. this._rQi = 0;
  200. this._websocket = null;
  201. // Check for full typed array support
  202. var bt = false;
  203. if (('Uint8Array' in window) &&
  204. ('set' in Uint8Array.prototype)) {
  205. bt = true;
  206. }
  207. // Check for full binary type support in WebSockets
  208. // Inspired by:
  209. // https://github.com/Modernizr/Modernizr/issues/370
  210. // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/websockets/binary.js
  211. var wsbt = false;
  212. try {
  213. if (bt && ('binaryType' in WebSocket.prototype ||
  214. !!(new WebSocket(ws_schema + '://.').binaryType))) {
  215. Util.Info("Detected binaryType support in WebSockets");
  216. wsbt = true;
  217. }
  218. } catch (exc) {
  219. // Just ignore failed test localhost connection
  220. }
  221. // Default protocols if not specified
  222. if (typeof(protocols) === "undefined") {
  223. protocols = 'binary';
  224. }
  225. if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) {
  226. protocols = 'binary';
  227. }
  228. if (!wsbt) {
  229. throw new Error("noVNC no longer supports base64 WebSockets. " +
  230. "Please use a browser which supports binary WebSockets.");
  231. }
  232. if (protocols != 'binary') {
  233. throw new Error("noVNC no longer supports base64 WebSockets. Please " +
  234. "use the binary subprotocol instead.");
  235. }
  236. return protocols;
  237. },
  238. open: function (uri, protocols) {
  239. var ws_schema = uri.match(/^([a-z]+):\/\//)[1];
  240. protocols = this.init(protocols, ws_schema);
  241. this._websocket = new WebSocket(uri, protocols);
  242. if (protocols.indexOf('binary') >= 0) {
  243. this._websocket.binaryType = 'arraybuffer';
  244. }
  245. this._websocket.onmessage = this._recv_message.bind(this);
  246. this._websocket.onopen = (function () {
  247. Util.Debug('>> WebSock.onopen');
  248. if (this._websocket.protocol) {
  249. this._mode = this._websocket.protocol;
  250. Util.Info("Server choose sub-protocol: " + this._websocket.protocol);
  251. } else {
  252. this._mode = 'binary';
  253. Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol);
  254. }
  255. if (this._mode != 'binary') {
  256. throw new Error("noVNC no longer supports base64 WebSockets. Please " +
  257. "use the binary subprotocol instead.");
  258. }
  259. this._eventHandlers.open();
  260. Util.Debug("<< WebSock.onopen");
  261. }).bind(this);
  262. this._websocket.onclose = (function (e) {
  263. Util.Debug(">> WebSock.onclose");
  264. this._eventHandlers.close(e);
  265. Util.Debug("<< WebSock.onclose");
  266. }).bind(this);
  267. this._websocket.onerror = (function (e) {
  268. Util.Debug(">> WebSock.onerror: " + e);
  269. this._eventHandlers.error(e);
  270. Util.Debug("<< WebSock.onerror: " + e);
  271. }).bind(this);
  272. },
  273. close: function () {
  274. if (this._websocket) {
  275. if ((this._websocket.readyState === WebSocket.OPEN) ||
  276. (this._websocket.readyState === WebSocket.CONNECTING)) {
  277. Util.Info("Closing WebSocket connection");
  278. this._websocket.close();
  279. }
  280. this._websocket.onmessage = function (e) { return; };
  281. }
  282. },
  283. // private methods
  284. _encode_message: function () {
  285. // Put in a binary arraybuffer
  286. // according to the spec, you can send ArrayBufferViews with the send method
  287. return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
  288. },
  289. _expand_compact_rQ: function (min_fit) {
  290. var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2;
  291. if (resizeNeeded) {
  292. if (!min_fit) {
  293. // just double the size if we need to do compaction
  294. this._rQbufferSize *= 2;
  295. } else {
  296. // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8
  297. this._rQbufferSize = (this._rQlen - this._rQi + min_fit) * 8;
  298. }
  299. }
  300. // we don't want to grow unboundedly
  301. if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
  302. this._rQbufferSize = MAX_RQ_GROW_SIZE;
  303. if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) {
  304. throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
  305. }
  306. }
  307. if (resizeNeeded) {
  308. var old_rQbuffer = this._rQ.buffer;
  309. this._rQmax = this._rQbufferSize / 8;
  310. this._rQ = new Uint8Array(this._rQbufferSize);
  311. this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
  312. } else {
  313. if (ENABLE_COPYWITHIN) {
  314. this._rQ.copyWithin(0, this._rQi);
  315. } else {
  316. this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
  317. }
  318. }
  319. this._rQlen = this._rQlen - this._rQi;
  320. this._rQi = 0;
  321. },
  322. _decode_message: function (data) {
  323. // push arraybuffer values onto the end
  324. var u8 = new Uint8Array(data);
  325. if (u8.length > this._rQbufferSize - this._rQlen) {
  326. this._expand_compact_rQ(u8.length);
  327. }
  328. this._rQ.set(u8, this._rQlen);
  329. this._rQlen += u8.length;
  330. },
  331. _recv_message: function (e) {
  332. try {
  333. this._decode_message(e.data);
  334. if (this.rQlen() > 0) {
  335. this._eventHandlers.message();
  336. // Compact the receive queue
  337. if (this._rQlen == this._rQi) {
  338. this._rQlen = 0;
  339. this._rQi = 0;
  340. } else if (this._rQlen > this._rQmax) {
  341. this._expand_compact_rQ();
  342. }
  343. } else {
  344. Util.Debug("Ignoring empty message");
  345. }
  346. } catch (exc) {
  347. var exception_str = "";
  348. if (exc.name) {
  349. exception_str += "\n name: " + exc.name + "\n";
  350. exception_str += " message: " + exc.message + "\n";
  351. }
  352. if (typeof exc.description !== 'undefined') {
  353. exception_str += " description: " + exc.description + "\n";
  354. }
  355. if (typeof exc.stack !== 'undefined') {
  356. exception_str += exc.stack;
  357. }
  358. if (exception_str.length > 0) {
  359. Util.Error("recv_message, caught exception: " + exception_str);
  360. } else {
  361. Util.Error("recv_message, caught exception: " + exc);
  362. }
  363. if (typeof exc.name !== 'undefined') {
  364. this._eventHandlers.error(exc.name + ": " + exc.message);
  365. } else {
  366. this._eventHandlers.error(exc);
  367. }
  368. }
  369. }
  370. };
  371. })();