websock.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Websock: high-performance binary WebSockets
  3. * Copyright (C) 2018 The noVNC Authors
  4. * Licensed under MPL 2.0 (see LICENSE.txt)
  5. *
  6. * Websock is similar to the standard WebSocket object but with extra
  7. * buffer handling.
  8. *
  9. * Websock has built-in receive queue buffering; the message event
  10. * does not contain actual data but is simply a notification that
  11. * there is new data available. Several rQ* methods are available to
  12. * read binary data off of the receive queue.
  13. */
  14. import * as Log from './util/logging.js';
  15. // this has performance issues in some versions Chromium, and
  16. // doesn't gain a tremendous amount of performance increase in Firefox
  17. // at the moment. It may be valuable to turn it on in the future.
  18. const ENABLE_COPYWITHIN = false;
  19. const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
  20. export default class Websock {
  21. constructor() {
  22. this._websocket = null; // WebSocket object
  23. this._rQi = 0; // Receive queue index
  24. this._rQlen = 0; // Next write position in the receive queue
  25. this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
  26. this._rQmax = this._rQbufferSize / 8;
  27. // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
  28. this._rQ = null; // Receive queue
  29. this._sQbufferSize = 1024 * 10; // 10 KiB
  30. // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
  31. this._sQlen = 0;
  32. this._sQ = null; // Send queue
  33. this._eventHandlers = {
  34. message: () => {},
  35. open: () => {},
  36. close: () => {},
  37. error: () => {}
  38. };
  39. }
  40. // Getters and Setters
  41. get sQ() {
  42. return this._sQ;
  43. }
  44. get rQ() {
  45. return this._rQ;
  46. }
  47. get rQi() {
  48. return this._rQi;
  49. }
  50. set rQi(val) {
  51. this._rQi = val;
  52. }
  53. // Receive Queue
  54. get rQlen() {
  55. return this._rQlen - this._rQi;
  56. }
  57. rQpeek8() {
  58. return this._rQ[this._rQi];
  59. }
  60. rQskipBytes(bytes) {
  61. this._rQi += bytes;
  62. }
  63. rQshift8() {
  64. return this._rQshift(1);
  65. }
  66. rQshift16() {
  67. return this._rQshift(2);
  68. }
  69. rQshift32() {
  70. return this._rQshift(4);
  71. }
  72. // TODO(directxman12): test performance with these vs a DataView
  73. _rQshift(bytes) {
  74. let res = 0;
  75. for (let byte = bytes - 1; byte >= 0; byte--) {
  76. res += this._rQ[this._rQi++] << (byte * 8);
  77. }
  78. return res;
  79. }
  80. rQshiftStr(len) {
  81. if (typeof(len) === 'undefined') { len = this.rQlen; }
  82. let str = "";
  83. // Handle large arrays in steps to avoid long strings on the stack
  84. for (let i = 0; i < len; i += 4096) {
  85. let part = this.rQshiftBytes(Math.min(4096, len - i));
  86. str += String.fromCharCode.apply(null, part);
  87. }
  88. return str;
  89. }
  90. rQshiftBytes(len) {
  91. if (typeof(len) === 'undefined') { len = this.rQlen; }
  92. this._rQi += len;
  93. return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
  94. }
  95. rQshiftTo(target, len) {
  96. if (len === undefined) { len = this.rQlen; }
  97. // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
  98. target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
  99. this._rQi += len;
  100. }
  101. rQslice(start, end = this.rQlen) {
  102. return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
  103. }
  104. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  105. // to be available in the receive queue. Return true if we need to
  106. // wait (and possibly print a debug message), otherwise false.
  107. rQwait(msg, num, goback) {
  108. if (this.rQlen < num) {
  109. if (goback) {
  110. if (this._rQi < goback) {
  111. throw new Error("rQwait cannot backup " + goback + " bytes");
  112. }
  113. this._rQi -= goback;
  114. }
  115. return true; // true means need more data
  116. }
  117. return false;
  118. }
  119. // Send Queue
  120. flush() {
  121. if (this._sQlen > 0 && this._websocket.readyState === WebSocket.OPEN) {
  122. this._websocket.send(this._encode_message());
  123. this._sQlen = 0;
  124. }
  125. }
  126. send(arr) {
  127. this._sQ.set(arr, this._sQlen);
  128. this._sQlen += arr.length;
  129. this.flush();
  130. }
  131. send_string(str) {
  132. this.send(str.split('').map(chr => chr.charCodeAt(0)));
  133. }
  134. // Event Handlers
  135. off(evt) {
  136. this._eventHandlers[evt] = () => {};
  137. }
  138. on(evt, handler) {
  139. this._eventHandlers[evt] = handler;
  140. }
  141. _allocate_buffers() {
  142. this._rQ = new Uint8Array(this._rQbufferSize);
  143. this._sQ = new Uint8Array(this._sQbufferSize);
  144. }
  145. init() {
  146. this._allocate_buffers();
  147. this._rQi = 0;
  148. this._websocket = null;
  149. }
  150. open(uri, protocols) {
  151. this.init();
  152. this._websocket = new WebSocket(uri, protocols);
  153. this._websocket.binaryType = 'arraybuffer';
  154. this._websocket.onmessage = this._recv_message.bind(this);
  155. this._websocket.onopen = () => {
  156. Log.Debug('>> WebSock.onopen');
  157. if (this._websocket.protocol) {
  158. Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
  159. }
  160. this._eventHandlers.open();
  161. Log.Debug("<< WebSock.onopen");
  162. };
  163. this._websocket.onclose = (e) => {
  164. Log.Debug(">> WebSock.onclose");
  165. this._eventHandlers.close(e);
  166. Log.Debug("<< WebSock.onclose");
  167. };
  168. this._websocket.onerror = (e) => {
  169. Log.Debug(">> WebSock.onerror: " + e);
  170. this._eventHandlers.error(e);
  171. Log.Debug("<< WebSock.onerror: " + e);
  172. };
  173. }
  174. close() {
  175. if (this._websocket) {
  176. if ((this._websocket.readyState === WebSocket.OPEN) ||
  177. (this._websocket.readyState === WebSocket.CONNECTING)) {
  178. Log.Info("Closing WebSocket connection");
  179. this._websocket.close();
  180. }
  181. this._websocket.onmessage = () => {};
  182. }
  183. }
  184. // private methods
  185. _encode_message() {
  186. // Put in a binary arraybuffer
  187. // according to the spec, you can send ArrayBufferViews with the send method
  188. return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
  189. }
  190. _expand_compact_rQ(min_fit) {
  191. const resizeNeeded = min_fit || this.rQlen > this._rQbufferSize / 2;
  192. if (resizeNeeded) {
  193. if (!min_fit) {
  194. // just double the size if we need to do compaction
  195. this._rQbufferSize *= 2;
  196. } else {
  197. // otherwise, make sure we satisy rQlen - rQi + min_fit < rQbufferSize / 8
  198. this._rQbufferSize = (this.rQlen + min_fit) * 8;
  199. }
  200. }
  201. // we don't want to grow unboundedly
  202. if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
  203. this._rQbufferSize = MAX_RQ_GROW_SIZE;
  204. if (this._rQbufferSize - this.rQlen < min_fit) {
  205. throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
  206. }
  207. }
  208. if (resizeNeeded) {
  209. const old_rQbuffer = this._rQ.buffer;
  210. this._rQmax = this._rQbufferSize / 8;
  211. this._rQ = new Uint8Array(this._rQbufferSize);
  212. this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
  213. } else {
  214. if (ENABLE_COPYWITHIN) {
  215. this._rQ.copyWithin(0, this._rQi);
  216. } else {
  217. this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
  218. }
  219. }
  220. this._rQlen = this._rQlen - this._rQi;
  221. this._rQi = 0;
  222. }
  223. _decode_message(data) {
  224. // push arraybuffer values onto the end
  225. const u8 = new Uint8Array(data);
  226. if (u8.length > this._rQbufferSize - this._rQlen) {
  227. this._expand_compact_rQ(u8.length);
  228. }
  229. this._rQ.set(u8, this._rQlen);
  230. this._rQlen += u8.length;
  231. }
  232. _recv_message(e) {
  233. this._decode_message(e.data);
  234. if (this.rQlen > 0) {
  235. this._eventHandlers.message();
  236. // Compact the receive queue
  237. if (this._rQlen == this._rQi) {
  238. this._rQlen = 0;
  239. this._rQi = 0;
  240. } else if (this._rQlen > this._rQmax) {
  241. this._expand_compact_rQ();
  242. }
  243. } else {
  244. Log.Debug("Ignoring empty message");
  245. }
  246. }
  247. }