websock.js 14 KB

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