websock.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. * Websock: high-performance buffering wrapper
  3. * Copyright (C) 2019 The noVNC Authors
  4. * Licensed under MPL 2.0 (see LICENSE.txt)
  5. *
  6. * Websock is similar to the standard WebSocket / RTCDataChannel object
  7. * but with extra 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 MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB
  19. // Constants pulled from RTCDataChannelState enum
  20. // https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/readyState#RTCDataChannelState_enum
  21. const DataChannel = {
  22. CONNECTING: "connecting",
  23. OPEN: "open",
  24. CLOSING: "closing",
  25. CLOSED: "closed"
  26. };
  27. const ReadyStates = {
  28. CONNECTING: [WebSocket.CONNECTING, DataChannel.CONNECTING],
  29. OPEN: [WebSocket.OPEN, DataChannel.OPEN],
  30. CLOSING: [WebSocket.CLOSING, DataChannel.CLOSING],
  31. CLOSED: [WebSocket.CLOSED, DataChannel.CLOSED],
  32. };
  33. // Properties a raw channel must have, WebSocket and RTCDataChannel are two examples
  34. const rawChannelProps = [
  35. "send",
  36. "close",
  37. "binaryType",
  38. "onerror",
  39. "onmessage",
  40. "onopen",
  41. "protocol",
  42. "readyState",
  43. ];
  44. export default class Websock {
  45. constructor() {
  46. this._websocket = null; // WebSocket or RTCDataChannel object
  47. this._rQi = 0; // Receive queue index
  48. this._rQlen = 0; // Next write position in the receive queue
  49. this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
  50. // called in init: this._rQ = new Uint8Array(this._rQbufferSize);
  51. this._rQ = null; // Receive queue
  52. this._sQbufferSize = 1024 * 10; // 10 KiB
  53. // called in init: this._sQ = new Uint8Array(this._sQbufferSize);
  54. this._sQlen = 0;
  55. this._sQ = null; // Send queue
  56. this._eventHandlers = {
  57. message: () => {},
  58. open: () => {},
  59. close: () => {},
  60. error: () => {}
  61. };
  62. }
  63. // Getters and Setters
  64. get readyState() {
  65. let subState;
  66. if (this._websocket === null) {
  67. return "unused";
  68. }
  69. subState = this._websocket.readyState;
  70. if (ReadyStates.CONNECTING.includes(subState)) {
  71. return "connecting";
  72. } else if (ReadyStates.OPEN.includes(subState)) {
  73. return "open";
  74. } else if (ReadyStates.CLOSING.includes(subState)) {
  75. return "closing";
  76. } else if (ReadyStates.CLOSED.includes(subState)) {
  77. return "closed";
  78. }
  79. return "unknown";
  80. }
  81. get sQ() {
  82. return this._sQ;
  83. }
  84. get rQ() {
  85. return this._rQ;
  86. }
  87. get rQi() {
  88. return this._rQi;
  89. }
  90. set rQi(val) {
  91. this._rQi = val;
  92. }
  93. // Receive Queue
  94. get rQlen() {
  95. return this._rQlen - this._rQi;
  96. }
  97. rQpeek8() {
  98. return this._rQ[this._rQi];
  99. }
  100. rQskipBytes(bytes) {
  101. this._rQi += bytes;
  102. }
  103. rQshift8() {
  104. return this._rQshift(1);
  105. }
  106. rQshift16() {
  107. return this._rQshift(2);
  108. }
  109. rQshift32() {
  110. return this._rQshift(4);
  111. }
  112. // TODO(directxman12): test performance with these vs a DataView
  113. _rQshift(bytes) {
  114. let res = 0;
  115. for (let byte = bytes - 1; byte >= 0; byte--) {
  116. res += this._rQ[this._rQi++] << (byte * 8);
  117. }
  118. return res;
  119. }
  120. rQshiftStr(len) {
  121. if (typeof(len) === 'undefined') { len = this.rQlen; }
  122. let str = "";
  123. // Handle large arrays in steps to avoid long strings on the stack
  124. for (let i = 0; i < len; i += 4096) {
  125. let part = this.rQshiftBytes(Math.min(4096, len - i));
  126. str += String.fromCharCode.apply(null, part);
  127. }
  128. return str;
  129. }
  130. rQshiftBytes(len) {
  131. if (typeof(len) === 'undefined') { len = this.rQlen; }
  132. this._rQi += len;
  133. return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
  134. }
  135. rQshiftTo(target, len) {
  136. if (len === undefined) { len = this.rQlen; }
  137. // TODO: make this just use set with views when using a ArrayBuffer to store the rQ
  138. target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
  139. this._rQi += len;
  140. }
  141. rQslice(start, end = this.rQlen) {
  142. return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
  143. }
  144. // Check to see if we must wait for 'num' bytes (default to FBU.bytes)
  145. // to be available in the receive queue. Return true if we need to
  146. // wait (and possibly print a debug message), otherwise false.
  147. rQwait(msg, num, goback) {
  148. if (this.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() {
  161. if (this._sQlen > 0 && this.readyState === 'open') {
  162. this._websocket.send(this._encodeMessage());
  163. this._sQlen = 0;
  164. }
  165. }
  166. send(arr) {
  167. this._sQ.set(arr, this._sQlen);
  168. this._sQlen += arr.length;
  169. this.flush();
  170. }
  171. sendString(str) {
  172. this.send(str.split('').map(chr => chr.charCodeAt(0)));
  173. }
  174. // Event Handlers
  175. off(evt) {
  176. this._eventHandlers[evt] = () => {};
  177. }
  178. on(evt, handler) {
  179. this._eventHandlers[evt] = handler;
  180. }
  181. _allocateBuffers() {
  182. this._rQ = new Uint8Array(this._rQbufferSize);
  183. this._sQ = new Uint8Array(this._sQbufferSize);
  184. }
  185. init() {
  186. this._allocateBuffers();
  187. this._rQi = 0;
  188. this._websocket = null;
  189. }
  190. open(uri, protocols) {
  191. this.attach(new WebSocket(uri, protocols));
  192. }
  193. attach(rawChannel) {
  194. this.init();
  195. // Must get object and class methods to be compatible with the tests.
  196. const channelProps = [...Object.keys(rawChannel), ...Object.getOwnPropertyNames(Object.getPrototypeOf(rawChannel))];
  197. for (let i = 0; i < rawChannelProps.length; i++) {
  198. const prop = rawChannelProps[i];
  199. if (channelProps.indexOf(prop) < 0) {
  200. throw new Error('Raw channel missing property: ' + prop);
  201. }
  202. }
  203. this._websocket = rawChannel;
  204. this._websocket.binaryType = "arraybuffer";
  205. this._websocket.onmessage = this._recvMessage.bind(this);
  206. this._websocket.onopen = () => {
  207. Log.Debug('>> WebSock.onopen');
  208. if (this._websocket.protocol) {
  209. Log.Info("Server choose sub-protocol: " + this._websocket.protocol);
  210. }
  211. this._eventHandlers.open();
  212. Log.Debug("<< WebSock.onopen");
  213. };
  214. this._websocket.onclose = (e) => {
  215. Log.Debug(">> WebSock.onclose");
  216. this._eventHandlers.close(e);
  217. Log.Debug("<< WebSock.onclose");
  218. };
  219. this._websocket.onerror = (e) => {
  220. Log.Debug(">> WebSock.onerror: " + e);
  221. this._eventHandlers.error(e);
  222. Log.Debug("<< WebSock.onerror: " + e);
  223. };
  224. }
  225. close() {
  226. if (this._websocket) {
  227. if (this.readyState === 'connecting' ||
  228. this.readyState === 'open') {
  229. Log.Info("Closing WebSocket connection");
  230. this._websocket.close();
  231. }
  232. this._websocket.onmessage = () => {};
  233. }
  234. }
  235. // private methods
  236. _encodeMessage() {
  237. // Put in a binary arraybuffer
  238. // according to the spec, you can send ArrayBufferViews with the send method
  239. return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
  240. }
  241. // We want to move all the unread data to the start of the queue,
  242. // e.g. compacting.
  243. // The function also expands the receive que if needed, and for
  244. // performance reasons we combine these two actions to avoid
  245. // unneccessary copying.
  246. _expandCompactRQ(minFit) {
  247. // if we're using less than 1/8th of the buffer even with the incoming bytes, compact in place
  248. // instead of resizing
  249. const requiredBufferSize = (this._rQlen - this._rQi + minFit) * 8;
  250. const resizeNeeded = this._rQbufferSize < requiredBufferSize;
  251. if (resizeNeeded) {
  252. // Make sure we always *at least* double the buffer size, and have at least space for 8x
  253. // the current amount of data
  254. this._rQbufferSize = Math.max(this._rQbufferSize * 2, requiredBufferSize);
  255. }
  256. // we don't want to grow unboundedly
  257. if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
  258. this._rQbufferSize = MAX_RQ_GROW_SIZE;
  259. if (this._rQbufferSize - this.rQlen < minFit) {
  260. throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
  261. }
  262. }
  263. if (resizeNeeded) {
  264. const oldRQbuffer = this._rQ.buffer;
  265. this._rQ = new Uint8Array(this._rQbufferSize);
  266. this._rQ.set(new Uint8Array(oldRQbuffer, this._rQi, this._rQlen - this._rQi));
  267. } else {
  268. this._rQ.copyWithin(0, this._rQi, this._rQlen);
  269. }
  270. this._rQlen = this._rQlen - this._rQi;
  271. this._rQi = 0;
  272. }
  273. // push arraybuffer values onto the end of the receive que
  274. _DecodeMessage(data) {
  275. const u8 = new Uint8Array(data);
  276. if (u8.length > this._rQbufferSize - this._rQlen) {
  277. this._expandCompactRQ(u8.length);
  278. }
  279. this._rQ.set(u8, this._rQlen);
  280. this._rQlen += u8.length;
  281. }
  282. _recvMessage(e) {
  283. this._DecodeMessage(e.data);
  284. if (this.rQlen > 0) {
  285. this._eventHandlers.message();
  286. if (this._rQlen == this._rQi) {
  287. // All data has now been processed, this means we
  288. // can reset the receive queue.
  289. this._rQlen = 0;
  290. this._rQi = 0;
  291. }
  292. } else {
  293. Log.Debug("Ignoring empty message");
  294. }
  295. }
  296. }